2D Arrays
Overview
A 1D array is a single line of lockers. But what if you need a grid? Think of a chessboard, a Bingo card, or an Excel spreadsheet. They have Rows and Columns.
A 2D Array is exactly that—a grid. In Java, it is literally an 'array of arrays'. You specify the row first, and then the column. It is the perfect tool anytime you need to map out data in 2-dimensional space.
1. Rows and Columns
When you interact with a 2D array, you provide two indexes: `grid[row][column]`. Just like 1D arrays, both rows and columns start counting at 0.
2. Nested Loops
To visit every single square on a chessboard, you need to go row by row, and inside each row, go square by square. This requires a loop inside of another loop (nested loops).
Syntax
You use double brackets `[][]` to define a 2D array.
// Creates a 3x3 grid (3 rows, 3 columns)
int[][] board = new int[3][3];
// Placing a piece in the exact center (Row 1, Column 1)
board[1][1] = 9;
// Array Literal for a 2D grid
int[][] matrix = {
{1, 2, 3}, // Row 0
{4, 5, 6}, // Row 1
{7, 8, 9} // Row 2
};
System.out.println(matrix[2][0]); // Prints 7 (Row 2, Column 0)The outer loop handles the rows. The inner loop handles the columns.
int[][] grid = { {1, 2}, {3, 4}, {5, 6} };
for (int row = 0; row < grid.length; row++) {
// grid[row].length gets the number of columns in this specific row
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println(); // Prints a new line after each row finishes
}Common Pitfalls
- Reversing the row and column order. Remember it's always `[row][col]`, which corresponds to `[y][x]` on a graph, NOT `[x][y]`.
Interview Tips
- In Java, 2D arrays can be 'Jagged'. This means Row 0 could have 5 columns, but Row 1 might only have 2 columns. They don't have to be perfect squares!
Real-World Example
2D arrays are used for building board games, managing theater seating, or image processing (pixels on a screen).
public class CinemaSeating {
public static void main(String[] args) {
// 0 means empty seat, 1 means booked seat
int[][] seats = {
{0, 0, 1}, // Front row
{1, 1, 1}, // Middle row
{0, 0, 0} // Back row
};
// Check if front row, middle seat is taken
if (seats[0][1] == 1) {
System.out.println("Seat taken.");
} else {
System.out.println("Seat is available!");
}
}
}