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 → 3
  • grid[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.length is 2 (rows)
  • a[0].length is 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.

TypeDefault value
int0
double0.0
booleanfalse
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

  1. If int[][] g = new int[2][5], how many rows? columns?
  2. What does g.length represent?
  3. What does g[0].length represent (rectangular)?
  4. What is stored in a new int 2D array before you assign anything?
  5. What element is g[1][0]?

← Back to Unit 4 topics