← Back to course

2D Arrays

You’ll be able to

A grid of rows and columns

A 2D array is an array of arrays — a grid. int[][] grid = {{1, 2, 3}, {4, 5, 6}}; has 2 rows and 3 columns. You access an element with two indices, grid[row][col], both zero-based. grid[0] is the first row {1, 2, 3}, and grid[1][2] is row 1, column 2.

Rows first, then columns

The first index selects the row, the second selects the column within that row. So grid[1][2] means "go to row 1, then column 2." Reading these in the right order is essential: grid[2][1] would be a different (and possibly invalid) element.

Counting rows and columns

For a rectangular 2D array, m.length gives the number of rows, and m[0].length gives the number of columns (the length of the first row). new int[3][4] therefore has 3 rows and 4 columns, all initialized to the default 0. To visit every cell, nest a column loop inside a row loop.

2D array dimensions
rows = m.length columns = m[0].length
Access is m[row][col], both zero-based. new int[R][C] has R rows and C columns.
Worked example

Trace this code: int[][] grid = {{1, 2, 3}, {4, 5, 6}}; then System.out.println(grid[1][2]);

  1. 1.Row 0 is {1, 2, 3}; row 1 is {4, 5, 6}.
  2. 2.grid[1] selects row 1: {4, 5, 6}.
  3. 3.grid[1][2] then selects column 2 of that row.
  4. 4.Column 2 of {4, 5, 6} is 6 (indices 0, 1, 2 → 4, 5, 6).
Answer: It prints 6 — row 1, column 2 of the grid.
Checkpoint

What does this print? `int[][] grid = {{1, 2, 3}, {4, 5, 6}};` then `System.out.println(grid[1][2]);`

Tip

Always read [row][col]: the first bracket is the row, the second is the column. Swapping them is the most common 2D-array mistake.

Checkpoint

What does this print? `int[][] m = new int[3][4];` then `System.out.println(m.length + " " + m[0].length);`

On the exam

To traverse a full grid, use for (int r = 0; r < m.length; r++) outside and for (int c = 0; c < m[0].length; c++) inside. The outer loop walks rows, the inner walks columns.

Answer the 2 checkpoints as you read.

Sign in to save your progress