VisualStudioTutor.com Java Tutorial All Lessons

Lesson 11 of 20

Arrays

Store and process multiple values using one-dimensional and two-dimensional arrays.

Learning objectives

  • Create arrays with a fixed number of elements.
  • Read and update elements using indexes.
  • Traverse arrays with for and enhanced for loops.
  • Calculate totals, averages, minimums, and maximums.
  • Create and read a two-dimensional array.

1. What is an array?

An array stores multiple values of the same type under one variable name. Array indexes begin at 0.

Example: create and access an array

int[] marks = {78, 65, 90, 84, 72};

System.out.println(marks[0]); // first element
System.out.println(marks[4]); // fifth element

marks[1] = 70; // update the second element

2. Processing an array with a loop

int[] marks = {78, 65, 90, 84, 72};
int total = 0;

for (int mark : marks) {
    total += mark;
}

double average = (double) total / marks.length;
System.out.printf("Average: %.2f%n", average);

3. Finding the highest value

int[] marks = {78, 65, 90, 84, 72};
int highest = marks[0];

for (int mark : marks) {
    if (mark > highest) {
        highest = mark;
    }
}

System.out.println("Highest: " + highest);

4. Two-dimensional arrays

A two-dimensional array can represent rows and columns.

int[][] sales = {
    {12, 15, 18},
    {10, 14, 20}
};

System.out.println(sales[0][2]); // 18

for (int row = 0; row < sales.length; row++) {
    for (int col = 0; col < sales[row].length; col++) {
        System.out.print(sales[row][col] + " ");
    }
    System.out.println();
}

Mini project: student mark analyser

public class MarkAnalyser {
    public static void main(String[] args) {
        int[] marks = {78, 65, 90, 84, 72};

        int total = 0;
        int highest = marks[0];
        int lowest = marks[0];

        for (int mark : marks) {
            total += mark;

            if (mark > highest) {
                highest = mark;
            }

            if (mark < lowest) {
                lowest = mark;
            }
        }

        double average = (double) total / marks.length;

        System.out.printf("Average: %.2f%n", average);
        System.out.println("Highest: " + highest);
        System.out.println("Lowest : " + lowest);
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
ArrayIndexOutOfBoundsExceptionAn index is below 0 or equal to/greater than array length.Use indexes from 0 to length - 1.
Using length()Arrays use a field, not a method.Use array.length.
Assuming an array can growJava arrays have fixed length.Use ArrayList when the collection size must change.

Summary

Arrays are efficient fixed-size containers for values of one type. The next lesson focuses on String, Java's main type for text processing.