Java Multidimensional Arrays
A multidimensional array is an array whose elements are themselves arrays. The most common form is the two-dimensional array, which behaves like a grid or table with rows and columns — perfect for spreadsheets, game boards, and matrices.
Creating a two-dimensional array
To declare a 2D array you use two pairs of square brackets. You can picture it as a table: the first index selects the row, and the second index selects the column within that row. Each inner set of braces represents one row of values.
Declaring a 2D array
public class Main {
public static void main(String[] args) {
// A 2-row, 3-column grid of numbers
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
// Read the value in row 1, column 2
System.out.println(grid[1][2]); // 6
// Change the value in row 0, column 0
grid[0][0] = 99;
System.out.println(grid[0][0]); // 99
}
}The first bracket always refers to the row and the second to the column. So grid[1][2] means row index 1, column index 2, which is the number 6 in the example above.
Looping through a 2D array
To visit every cell you nest one loop inside another. The outer loop walks through the rows, and the inner loop walks through the columns of the current row. Note that grid.length gives the number of rows, while grid[i].length gives the number of columns in row i.
Nested for loops over a grid
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println(); // new line after each row
}
}
}You can also use nested for-each loops when you only need the values. The outer loop hands you one row (an int array) at a time, and the inner loop reads each value inside that row.
Nested for-each loops
public class Main {
public static void main(String[] args) {
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
for (int[] row : grid) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}- A 2D array is an array of arrays — each element is itself a row.
- Use two indexes: the first for the row, the second for the column.
- grid.length is the number of rows; grid[i].length is the width of row i.
- Java also supports 3D and higher arrays, but two dimensions cover most everyday needs.