Java Multi-dimensional Arrays
In this page:
Declaring 2D Arrays
A two-dimensional array is really an array whose elements are themselves arrays, which is how Java represents grid-like data such as a spreadsheet, a game board, or a matrix in linear algebra. You declare one with int[][] grid = new int[rows][cols];.
Example: Declaring 2D Arrays
public class Main {
public static void main(String[] args) {
int[][] grid = new int[2][3];
grid[0][0] = 1;
System.out.println(grid[0][0]);
}
}
Login to try C/C++/Java/PHP code in the editor
Accessing 2D Array Elements
To reach a specific cell, index the row first and then the column, like grid[2][3] for row 2, column 3 — mixing up the order is a common source of subtle bugs when the array isn't square. Both indices are still zero-based, same as a normal array.
Example: Accessing 2D Array Elements
public class Main {
public static void main(String[] args) {
int[][] grid = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
System.out.println(grid[2][3]); // row 2, column 3
}
}
Login to try C/C++/Java/PHP code in the editor
Iterating 2D Arrays
Nested loops are the standard way to walk a 2D array: the outer loop advances the row index, and the inner loop advances the column index within that row, visiting every cell exactly once. This pattern generalizes directly to 3D arrays by adding one more nested loop.
Example: Iterating 2D Arrays
public class Main {
public static void main(String[] args) {
int[][] grid = {{1, 2}, {3, 4}};
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
}
}
}
Login to try C/C++/Java/PHP code in the editor
Jagged Arrays
A jagged array is a 2D array where each row can be a different length — you declare it with only the row dimension fixed (int[][] jagged = new int[3][];) and then allocate each row's array separately with whatever size that row needs. This is useful when your data genuinely isn't rectangular, like a list of sentences with varying word counts.
Example: Jagged Arrays
public class Main {
public static void main(String[] args) {
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{1, 2};
jagged[2] = new int[]{1, 2, 3};
System.out.println(jagged[2].length);
}
}
Login to try C/C++/Java/PHP code in the editor
3D Arrays
A 3D array extends the same idea one level further, effectively an array of 2D arrays, useful for representing volumetric data like a Rubik's cube state or a 3D grid in a simulation. Each additional dimension multiplies the total memory used, so large 3D arrays can get expensive quickly.
Example: 3D Arrays
public class Main {
public static void main(String[] args) {
int[][][] cube = new int[2][2][2];
cube[0][1][1] = 5;
System.out.println(cube[0][1][1]);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: