2D Arrays
A 2D array is an "array of arrays" — the first index is the row, the second is the column.
It stores grid-like data — like a tic-tac-toe board, or a matrix.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6 (row 1, col 2)- 2D array = array of arrays
- Access with grid[row][col]
- Great for matrix/grid data
In Java, a 2D array is actually an "array of arrays" (not one continuous grid, like in C) — which is why every row can have a different length — this is called a "jagged array" (forming something like a triangle shape). It's more flexible than a normal rectangular grid, for when data is naturally uneven (like each student in a class having a different number of subjects).
int[][] jagged = new int[3][];
jagged[0] = new int[]{1};
jagged[1] = new int[]{1, 2};
jagged[2] = new int[]{1, 2, 3};There are two common ways to traverse a 2D array: a nested for loop (with an index, when you need the position too — like modifying grid[i][j]), or a nested for-each (when you only need the values, simpler code, but no index).
for (int[] row : grid) {
for (int val : row) {
System.out.print(val + " ");
}
}Java also supports 3D (int[][][]) or even more dimensions — an "array of array of arrays". Practical use is rare (mostly scientific computing, 3D grids/voxels), 2D is by far the most common in real projects. The concept stays the same — just one more level of nesting.
2D arrays are used for: matrix operations (addition, multiplication — linear algebra), game boards (chess, tic-tac-toe — each cell is a position), image data (pixels in rows/columns, each cell a color value), and storing spreadsheet-like tabular data where both rows and columns are meaningful.