AP® Computer Science A · Unit 4 · Topic 4.11

A 2D Array Is an Array of Arrays

A 2D array in Java isn't a true rectangle — it's an array whose elements are themselves arrays, one per row. Each row array stores its own length, so rows and columns are counted separately.

Java has no built-in rectangular grid type. When you write int[][] g, you're really making an array whose elements are references to other arrays. The outer array holds one reference per row; each row is its own independent int[] array living somewhere in memory. So a grid is an array of arrays, stacked conceptually into rows and columns, but structurally just one array pointing at several others.

This matters for how you measure the grid. g.length counts the elements of the outer array, which are the rows, so it gives the number of rows. To get the number of columns, you have to ask one specific row array how long it is, using g[0].length (or any other valid row index). There is no single property that reports 'columns' directly, because the grid's column count is really just a property of whichever row you check.

This picture carries forward into every grid traversal you write. Nested loops work precisely because the outer loop walks the outer array (rows) and the inner loop walks whichever row array that reference points to (columns). It also explains ragged arrays, where rows can have different lengths, since each row is its own separate array and nothing forces them to match.

Key terms

2D array
An array whose elements are themselves arrays, used in Java to represent a grid.
outer array
The top-level array in a 2D array, whose elements are references to the row arrays.
row array
One of the inner arrays referenced by the outer array, holding the values in a single row.
ragged array
A 2D array whose row arrays have different lengths, since each row is a separate, independent array.

Watch it explained

  1. How it worksHow does an array of references to row arrays produce a table in memory?
  2. Worked exampleTrace int[][] g = new int[3][4]; and find what g.length and g[0].length each give.
  3. Common mistakeWhy isn't grid.length the number of columns?
  4. Going furtherWhat changes in the picture when two rows of a 2D array point at the same row array?

Check yourself

Your turn1 of 2
int[][] g = new int[8][7]; What does g.length + g[0].length evaluate to?

End of topic.