Topic 4.11 — Exploring 2D Arrays
Goal: understand what a 2D array represents, how rows/columns are organized, and how to reason about indexes and dimensions before you start traversing.
The big idea
A 2D array is an “array of arrays.” You can think of it like a table: rows and columns.
Most 2D mistakes come from mixing up which index is the row and which is the column.
Row-major indexing
In Java, 2D arrays are typically accessed like:
grid[row][col]
| Expression | Meaning |
|---|---|
grid.length | # of rows |
grid[0].length | # of columns (assuming at least 1 row) |
grid[r].length | # of columns in row r (important for jagged arrays) |
Visual model (table idea)
If grid has 3 rows and 4 columns, indexes look like this:
grid[0][0] grid[0][1] grid[0][2] grid[0][3]
grid[1][0] grid[1][1] grid[1][2] grid[1][3]
grid[2][0] grid[2][1] grid[2][2] grid[2][3]
Rectangular vs jagged arrays
A rectangular 2D array has the same number of columns in every row. A jagged 2D array can have rows with different lengths.
// Rectangular (3x4)
int[][] a = new int[3][4];
// Jagged (rows can vary)
int[][] b = new int[3][];
b[0] = new int[2];
b[1] = new int[5];
b[2] = new int[1];
Why jagged matters for loops
If you assume every row has grid[0].length columns, you can go out of bounds on jagged arrays.
Safer inner loop:
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
// grid[r][c]
}
}
Accessing elements
int value = grid[2][1]; // row 2, column 1
grid[0][3] = 99; // update row 0, column 3
Always read it as [row][col].
Exam mindset: dimensions first
- Identify #rows with
grid.length - Identify #cols with
grid[0].length(rectangular) orgrid[r].length(jagged) - Then decide loop bounds
Quick self-check
- If
grid.lengthis 5, how many rows? - If
grid[0].lengthis 8 (rectangular), how many columns? - What does
grid[3][0]refer to? - Why is
grid[r].lengthsafer thangrid[0].lengthfor jagged arrays? - Write the nested loop bounds to visit every element in a jagged 2D array.