Topic 4.12 — 2D Array Creation and Access
Goal: create 2D arrays, understand default values, and access/update elements using
grid[row][col].
The big idea
Creating a 2D array means choosing the number of rows and columns (for rectangular arrays).
Access is always [row][col], and indexes start at 0.
When tracing, always identify dimensions first: grid.length (rows) and grid[0].length (cols).
Creation (rectangular)
// 3 rows, 4 columns
int[][] grid = new int[3][4];
grid.length→ 3grid[0].length→ 4
Initialize with values (literal form)
You can create and fill in one line:
int[][] a = {
{1, 2, 3},
{4, 5, 6}
};
a.lengthis 2 (rows)a[0].lengthis 3 (columns in row 0)
Access + update
int x = a[1][2]; // row 1, col 2 -> 6
a[0][1] = 99; // change row 0, col 1
Read it as: “in row 1, column 2.”
Default values
When you use new to create arrays, Java fills them with defaults.
| Type | Default value |
|---|---|
int | 0 |
double | 0.0 |
boolean | false |
Objects (like String) | null |
Common errors
- Mixing up row/col (writing
[col][row]) - Using
<=in loop bounds (off-by-one) - Assuming every row has the same length in a jagged array
// ✅ safe for jagged arrays
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
// grid[r][c]
}
}
Quick self-check
- If
int[][] g = new int[2][5], how many rows? columns? - What does
g.lengthrepresent? - What does
g[0].lengthrepresent (rectangular)? - What is stored in a new
int2D array before you assign anything? - What element is
g[1][0]?