Unit 4 · 15 min
4.11 2D Array Creation and Access
A 2D array is an array whose elements are rows, and each row is an ordinary 1D array.
Summary, objectives and course and exam description (CED) codes
A two-dimensional (2D) array is stored as an array of arrays: each row is a one-dimensional (1D) array. You create it with new (every element gets a default value) or with an initializer list of 1D initializer lists, and you reach one element with [row][col]. The number of rows is arr.length and the number of columns is arr[0].length.
By the end of this session you can
- 4.11.A Develop code used to represent collections of related data using two-dimensional (2D) array objects.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. A 2D array is an array of arrays
A two-dimensional (2D) array stores related data in rows and columns, such as seats in a cinema or scores per player per round. Java stores it as an array of arrays: the outer array holds the rows, and each row is a 1D array 4.11.A.1. So creating and indexing a 2D array works much like a 1D array, with one extra pair of brackets 4.11.A.1.
Like a 1D array, a 2D array’s size is set when it is created and cannot change 4.11.A.1. It can store primitive data (int, double, boolean) or object references (String, or any class) 4.11.A.1.
int[][] seats = new int[2][3]; // 2 rows, 3 columns of int
String[][] board = new String[3][3]; // 3 rows, 3 columns of references
System.out.println(seats.length + " rows, " + seats[0].length + " columns");
System.out.println(board.length * board[0].length + " squares");
Output:
2 rows, 3 columns
9 squares
Picture seats like this:
| column 0 | column 1 | column 2 | |
|---|---|---|---|
| row 0 | seats[0][0] |
seats[0][1] |
seats[0][2] |
| row 1 | seats[1][0] |
seats[1][1] |
seats[1][2] |
Scope note: every 2D array on the AP® exam is rectangular (every row has the same length). Arrays with rows of different lengths are outside the course 4.11.A.1.
2. Creating with new: default values
When you create a 2D array with the keyword new, every element starts at the default value for its type 4.11.A.2:
| Element type | Default value |
|---|---|
int |
0 |
double |
0.0 |
boolean |
false |
any reference type (String, a class) |
null |
int[][] counts = new int[2][2];
double[][] prices = new double[2][2];
boolean[][] booked = new boolean[2][2];
String[][] names = new String[2][2];
System.out.println(counts[1][1] + " " + prices[0][1] + " " + booked[1][0] + " " + names[0][0]);
Output:
0 0.0 false null
Watch out: names[0][0].length() would throw a NullPointerException, because the element holds null and not a String object.
3. Creating with an initializer list
An initializer list for a 2D array is a list of initializer lists: each inner list is one row, written like a 1D array 4.11.A.3. Java counts the rows and columns for you.
int[][] scores = { {12, 15, 9, 20},
{18, 11, 14, 16},
{10, 19, 13, 17} };
String[][] menu = { {"soup", "salad"},
{"pasta", "rice"} };
System.out.println(scores.length + " x " + scores[0].length);
System.out.println(menu[1][0]);
Output:
3 x 4
pasta
4. Reading and changing one element: [row][col]
Two indexes in square brackets reach one element: arr[row][col] 4.11.A.4. For the AP® exam, the first index is the row and the second index is the column 4.11.A.4. The same expression reads a value or, on the left of =, changes it.
int[][] scores = { {12, 15, 9, 20},
{18, 11, 14, 16},
{10, 19, 13, 17} };
System.out.println(scores[1][2]); // row 1, column 2
scores[2][0] = scores[0][3] + 5; // change row 2, column 0
scores[0][1]++;
System.out.println(scores[2][0] + " " + scores[0][1]);
Output:
14
25 16
The grid after the two changes:
| col 0 | col 1 | col 2 | col 3 | |
|---|---|---|---|---|
| row 0 | 12 | 16 | 9 | 20 |
| row 1 | 18 | 11 | 14 | 16 |
| row 2 | 25 | 19 | 13 | 17 |
5. One row as a 1D array
Use the array name with a single pair of brackets, arr[r], to get row r as a 1D array 4.11.A.5. This is a reference to the real row, not a copy, so changes through it change the 2D array.
double[][] rain = { {2.5, 0.0, 1.0},
{4.0, 3.5, 0.5} };
double[] week2 = rain[1]; // the whole second row
System.out.println(week2.length);
week2[0] = 9.9; // changes rain[1][0] too
System.out.println(rain[1][0]);
Output:
3
9.9
Watch out: there is no single-bracket way to get a column. A column must be built with a loop over the rows.
6. Size, valid indexes and ArrayIndexOutOfBoundsException
For a 2D array named grid 4.11.A.6:
| What you want | Expression | Valid index values |
|---|---|---|
| Number of rows | grid.length |
rows 0 to grid.length - 1 |
| Number of columns | grid[0].length (the length of any row) |
columns 0 to grid[0].length - 1 |
Any index outside these ranges throws an ArrayIndexOutOfBoundsException when the program runs 4.11.A.6.
String[][] maze = new String[4][6];
System.out.println("rows: " + maze.length);
System.out.println("columns: " + maze[0].length);
System.out.println("last row index: " + (maze.length - 1));
maze[3][6] = "#"; // column 6 does not exist
Output:
rows: 4
columns: 6
last row index: 3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
The message says “length 6” because the bad index was the column: each row has length 6, so the last column is 5.
Lock it in: memory hooks
- Index orderRC like a remote control: Row first, then Column.
- Counting rows and columnsarr.length counts the shelves; arr[0].length counts the boxes on one shelf.
- Default valuesNumbers start at zero, booleans start false, objects start with nothing (null).
Common misconceptions
"In grid[2][5], the first number is the column, like x before y in math."
Not quite. On the AP® exam the first index is always the row and the second index is the column: grid[row][col].
"grid.length gives the total number of elements."
Not quite. grid.length is the number of rows. The number of columns is grid[0].length. The total is grid.length * grid[0].length.
"A new String[3][3] is full of empty strings."
Not quite. String is a reference type, so every element starts as null. Only int (0), double (0.0) and boolean (false) get non-null defaults.
"You can add a row to a 2D array later."
Not quite. The size of a 2D array is fixed when it is created. To get more rows you must create a new, larger 2D array and copy the elements.
Exam traps
- arr.length is rows, not columns, and not the total number of elements.
- The last valid element is arr[arr.length - 1][arr[0].length - 1], not arr[arr.length][arr[0].length].
- A new 2D array of String or another class holds null in every element, so calling a method on one throws a NullPointerException.
- arr[r] is a reference to the row, not a copy: changing it changes the 2D array.
2PracticeRecall it, then check yourself
In 30 seconds
- A 2D array is an array of arrays; its size is fixed when it is created.
- new int[3][4] makes 3 rows and 4 columns, all set to the default value for the type.
- An initializer list holds one inner list per row: {{1, 2}, {3, 4}}.
- arr[r][c] reads or changes one element; arr[r] is the whole row as a 1D array.
- Rows: arr.length. Columns: arr[0].length. Valid indexes run from 0 to length - 1.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 4 questions
Checkpoint: 2D Array Creation and Access
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
2D arraytap to flip
An array of arrays that stores related data in rows and columns; each element is reached with arr[row][col].
Example and CED codes -
Arraytap to flip
An object that stores a fixed number of values of the same type, either primitive values or object references, reached by an index.
Example and CED codes -
Indextap to flip
The position of a character in a String, counted from 0. Valid indices run from 0 to length() - 1.
Example and CED codes -
Row-major ordertap to flip
A 2D array traversal that moves across each row, left to right, before going down to the next row.
Example and CED codes -
Object referencetap to flip
The value a reference variable holds: it can be thought of as the memory address of the object.
Example and CED codes -
nulltap to flip
A special literal meaning a reference variable is not associated with any object.
Example and CED codes
Questions students ask
How do you declare and create a 2D array in Java?
Write the type with two pairs of brackets, then use new with the number of rows and columns, for example int[][] seats = new int[5][8]; for 5 rows and 8 columns. You can also use an initializer list such as int[][] grid = {{1, 2}, {3, 4}};.
How do you get the number of rows and columns of a 2D array?
For a 2D array named arr, arr.length is the number of rows and arr[0].length is the number of columns (the length of the first row).
What are the default values in a new 2D array?
0 for int, 0.0 for double, false for boolean, and null for any reference type such as String.
Are jagged (nonrectangular) 2D arrays on the AP® Computer Science A exam?
No. Only rectangular 2D arrays, where every row has the same length, are in scope for the AP® exam.