Grade 12 Computer Science · Two-dimensional arrays

An array whose every item is an array

Why this picture explains almost everything.

Three rows, four cells, and one length

You create a grid of three rows with four cells in each, and ask it for its length. The answer is not 12, and not 4 either. And if you look for a command that returns how many columns the grid has, you find there is none at all. What did we actually create?

A game board, a table of grades, an image of pixels — all of these are a grid of cells in two dimensions. The language does not give a “grid” as a separate structure; it gives something simpler, and from it all the rules follow.

The outer structure holds rows; each row is an array of cells.
int[][] grid = new int[3][4];   // 3 rows, 4 cells in each

System.out.println(grid.length);      // 3 — the number of rows
System.out.println(grid[0].length);   // 4 — cells in the first row

grid[1][2] = 7;                 // row 1, cell 2 within it
int[] secondRow = grid[1];      // a row is an array in its own right

The two lengths

This is the detail most often confused, and the picture solves it with nothing to remember. The outer structure’s length is how many rows there are. A row’s length is asked of the row itself, not of the outer structure — because the row is an array in its own right. There is no operation returning a “number of columns”, and there cannot be: the rows need not be of the same length, so the question is undefined at the level of the whole structure.

The questionWhom one asks
How many rowsThe outer structure
How many cells in a rowThe row itself
How many columnsNo one — it is undefined

Example 1 — why a row is an array

  1. The first position returns an item.
  2. And the items are arrays.
  3. So it can be kept in a variable.

Example 2 — why there is no number of columns

  1. Each row is an independent array.
  2. And its length is its own.
  3. So there is no single number for them all.
No command asks grid how many columns it has — only each row knows its own length.