Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Multidimensional arrays

Data often has the shape of a table: seats in a hall, cells of a game board, students' grades by subject. Java uses a two-dimensional array for it — an array whose elements are themselves row arrays.

Creating a table

A two-dimensional array type has two pairs of brackets: int[][]. Values are given with nested curly braces — each inner pair describes one row:

void main() {
    int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6}
    };
    IO.println(matrix[0][2]);
    IO.println(matrix[1][0]);
}

Output:

3
4

The first index picks the row, the second picks the column in it. Both start at zero.

Sizes

matrix.length is the number of rows, and matrix[i].length is the length of a particular row. An empty table is created with new and two sizes; the elements get default values:

void main() {
    int[][] seats = new int[3][4];
    seats[1][2] = 1;
    IO.println("Rows: " + seats.length);
    IO.println("Seats per row: " + seats[0].length);
    IO.println(seats[1][2] + " " + seats[1][3]);
}

Output:

Rows: 3
Seats per row: 4
1 0

There can be more than two dimensions, for example int[][][], but such arrays are rare in practice.

Nested loops

To go through every element, use two loops: the outer one walks the rows, the inner one the elements of a row:

void main() {
    int[][] board = {
        {1, 0, 1},
        {0, 1, 0},
        {1, 0, 1}
    };
 
    for (int row = 0; row < board.length; row++) {
        for (int col = 0; col < board[row].length; col++) {
            IO.print(board[row][col] == 1 ? "X " : ". ");
        }
        IO.println();
    }
}

Output:

X . X
. X .
X . X

for-each over a table

With for-each the outer loop gets whole rows, that is int[] arrays, and the inner loop gets the numbers:

void main() {
    int[][] sales = {
        {120, 80},
        {95, 110},
        {60, 70}
    };
    int total = 0;
 
    for (int[] week : sales) {
        for (int amount : week) {
            total += amount;
        }
    }
 
    IO.println("Total sales: $" + total);
}

Output:

Total sales: $535

Jagged arrays

The rows of a two-dimensional array do not have to be the same length. Such an array is called jagged. Arrays.deepToString() is handy for printing it:

void main() {
    int[][] triangle = new int[3][];
    triangle[0] = new int[]{1};
    triangle[1] = new int[]{1, 1};
    triangle[2] = new int[]{1, 2, 1};
    IO.println(Arrays.deepToString(triangle));
}

Output:

[[1], [1, 1], [1, 2, 1]]

new int[3][] creates only the outer array with three empty slots, and rows of different lengths are added later. A plain Arrays.toString() on a two-dimensional array would print internal descriptions of the rows instead of numbers.

Common mistake

It is easy to mix up the number of rows and columns. If the table is not square, using matrix.length in the inner loop runs past the end of a row:

void main() {
    int[][] matrix = {
        {1, 2},
        {3, 4},
        {5, 6}
    };
 
    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix.length; col++) {
            IO.print(matrix[row][col] + " ");
        }
    }
}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2

The inner loop needs the length of the current row: col < matrix[row].length.

Thanks for reading!

Donate to the site — we work hard for you.