Remember arrays? A row of lockers. Now imagine a whole grid of lockers — rows and columns. That is a multi-dimensional array. It is basically an array of arrays.
The most common type is the 2D array. Think of it like a spreadsheet with rows and columns, or a chessboard, or a pixel grid on a screen.
Creating a 2D Array
You declare a 2D array with two sets of square brackets. The first is for rows, the second for columns.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(matrix[0][0]);
System.out.println(matrix[1][2]);
This creates a 3x3 grid. matrix[0][0] gives you the top-left
element (1), and matrix[1][2] gives you the element in row 1,
column 2 (6).
Nested Loops with 2D Arrays
To go through every element in a 2D array, you need nested loops. The outer loop goes through the rows, the inner loop goes through the columns.
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
This prints the entire matrix in grid form. Notice we use matrix.length
for the number of rows and matrix[i].length for the number of columns
in each row.
You can also use the enhanced for loop with 2D arrays. Each row is itself an array, so the outer for-each gives you a row, and the inner for-each gives you each element.
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}