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.
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 rightThe 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 question | Whom one asks |
|---|---|
| How many rows | The outer structure |
| How many cells in a row | The row itself |
| How many columns | No one — it is undefined |
Example 1 — why a row is an array
- The first position returns an item.
- And the items are arrays.
- So it can be kept in a variable.
Example 2 — why there is no number of columns
- Each row is an independent array.
- And its length is its own.
- So there is no single number for them all.