AP Computer Science A · Study guide

2D Array Creation and Access

AP® Computer Science A · Data Collections

2D Array Creation and Access

Representing a table of related data with a two-dimensional array: arrays of arrays, creating 2D arrays with new and with initializer lists, default values, accessing elements with [row][col], working with whole rows, and finding the number of rows and columns.

Big Picture

A 2D array is stored as an array of arrays, so it is created and indexed much like a 1D array. Its size is established when it is created and cannot be changed, and it can store primitive data or object references. Elements created with new start at the default value for their type; an initializer list of initializer lists creates and fills a 2D array at once. The brackets [row][col] access and modify an element, a single set of brackets gives a whole row, arr.length is the number of rows, and arr[0].length is the number of columns.

1An Array of Arrays

Many kinds of data come in tables: seats in a theater, cells in a spreadsheet, pixels in an image, squares on a game board. A two-dimensional array represents a collection of related data arranged in rows and columns. In Java, a 2D array is stored as an array of arrays: an outer array whose elements are references to rows, where each row is an ordinary 1D array.

Because of this structure, 2D arrays are created and indexed in a way that closely follows 1D arrays. The type int[][] is read as "array of int[]". The size of a 2D array is established at the time of creation and cannot be changed afterward, just like a 1D array, and the elements can be primitive values or object references. The 2D arrays used here are rectangular: every row has the same number of columns.

Figure 1. A 2D array is stored as an array of arrays: the outer array holds a reference to each row, and each row is a 1D array.
1D array2D array
Declare and createint[] a = new int[4];int[][] g = new int[3][4];
Initializer list{1, 2, 3}{ {1, 2, 3}, {4, 5, 6} }
Access an elementa[i]g[row][col]
Sizea.lengthg.length rows, g[0].length columns
Can the size change?NoNo

2Creating a 2D Array With new

The expression new int[3][4] creates a 2D array with 3 rows and 4 columns. The first number is the number of rows and the second is the number of columns. When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type: 0 for int, 0.0 for double, false for boolean, and null for a reference type.

Creating with new is the right choice when the values will be computed or read later, for example when a program fills a grid from a file or a calculation. The defaults give every element a known starting value, which algorithms such as counting can rely on.

Element typeDefault value after new
int0
double0.0
booleanfalse
Any reference type (String, objects)null
Worked Example 1 Creating with new

Rows, Columns, and Default Values

Predict the output.

Code
int[][] grid = new int[3][4];
System.out.println(grid.length);
System.out.println(grid[0].length);
System.out.println(grid[2][3]);
grid[1][2] = 9;
grid[0][0] = grid[1][2] + 1;
System.out.println(grid[1][2] + " " + grid[0][0]);
Output
3
4
0
9 10
  1. 1new int[3][4] creates 3 rows of 4 columns; every element starts at 0.
  2. 2grid.length is the number of rows, 3; grid[0].length is the number of columns, 4.
  3. 3grid[2][3] is the last element and still holds its default, 0.
  4. 4Assignment uses the same [row][col] brackets: 9 is stored, then 9 + 1 = 10.
Result: The output is 3, 4, 0, and 9 10. A 2D array created with new has a fixed number of rows and columns, and its elements start at the default value.
Worked Example 2 Default values

Every Element Type Has a Default

Predict the output.

Code
double[][] heights = new double[2][3];
boolean[][] lit = new boolean[2][2];
String[][] labels = new String[2][2];
System.out.println(heights[1][2]);
System.out.println(lit[0][1]);
System.out.println(labels[1][0]);
labels[1][0] = "exit";
System.out.println(labels[1][0].length());
Output
0.0
false
null
4
  1. 1double elements start at 0.0 and boolean elements at false.
  2. 2Reference elements, such as String, start at null: no object yet.
  3. 3After assignment the element refers to "exit", and its length() is 4.
Result: The output is 0.0, false, null, and 4. A 2D array can store primitive data or object reference data, and new elements take the default value for their type.
Worked Example 3 Reference elements

Using an Element That Is Still null

What happens?

Code
String[][] labels = new String[2][2];
labels[0][0] = "go";
System.out.println(labels[0][0].length());
System.out.println(labels[1][1].length());
  1. 1labels[0][0] refers to "go", so length() returns 2.
  2. 2labels[1][1] was never assigned and holds null; calling a method on it throws a NullPointerException.
Result: The program prints 2 and then stops with a NullPointerException. Elements of a 2D array of objects must be assigned objects before methods are called on them.
Common Mistake 1 · Calling Methods on Default null Elements

A 2D array of String or other objects starts full of null. Calling a method on an element that has not been assigned an object throws a NullPointerException. Assign each element before using it.

3Initializer Lists

The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays; for example, int[][] arr2D = { {1, 2, 3}, {4, 5, 6} };. Each inner list becomes one row, in order, so this array has 2 rows and 3 columns. The size of the array comes from the lists themselves, and no new expression is needed.

Writing each inner list on its own line makes the table shape visible in the code. Every inner list must have the same number of values so that the array is rectangular, and the inner braces are required: a flat list of numbers is a 1D initializer and does not compile as a 2D array.

Figure 2. The initializer list for a 2D array consists of initializer lists that represent 1D arrays, one for each row.
Worked Example 4 Initializer lists

Creating and Filling at Once

Predict the output.

Code
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
System.out.println(seats.length + " rows, " + seats[0].length + " columns");
System.out.println(seats[0][2]);
System.out.println(seats[1][0]);
Output
2 rows, 3 columns
7
2
  1. 1Two inner lists make two rows; each has three values, so there are three columns.
  2. 2seats[0][2] is row 0, column 2: 7.
  3. 3seats[1][0] is row 1, column 0: 2.
Result: The output is 2 rows, 3 columns, then 7 and 2. An initializer list of initializer lists creates a 2D array whose size matches the lists.
Worked Example 5 Initializer syntax

Missing the Inner Lists

Explain the compile error.

Code that does not compile
int[][] grid = {1, 2, 3};
  1. 1Each element of a 2D array is a row, an int[], so each item in the outer list must itself be a list.
  2. 2The fix wraps the values in inner braces: int[][] grid = { {1, 2, 3} }; creates one row of three columns.
Result: The code does not compile: 1 is an int, but the outer list needs int[] rows. A 2D initializer list consists of 1D initializer lists.

4Accessing Elements by Row and Column

The square brackets [row][col] are used to access and modify an element in a 2D array. When accessing the element at arr[first][second], the first index is used for rows and the second index is used for columns. So grid[1][2] is the element in row 1, column 2, and grid[1][2] = 9; stores 9 there.

Both indices start at 0. The element in the top-left corner is grid[0][0], and moving down increases the row index while moving right increases the column index. Mixing up the order is the most common 2D mistake, so it helps to say "row, then column" every time an element is written.

Figure 3. In arr[first][second], the first index is the row and the second index is the column.
Worked Example 6 Last element

Computing Positions From Lengths

Predict the output.

Code
String[][] map = { {"tree", "path", "pond"}, {"path", "rock", "path"} };
int lastRow = map.length - 1;
int lastCol = map[0].length - 1;
System.out.println(map[lastRow][lastCol]);
map[0][1] = "bridge";
System.out.println(map[0][1] + " beside " + map[0][2]);
Output
path
bridge beside pond
  1. 1Last row is map.length - 1 = 1; last column is map[0].length - 1 = 2.
  2. 2map[1][2] is "path".
  3. 3Modifying map[0][1] replaces "path" with "bridge" in row 0.
Result: The output is path, then bridge beside pond. The last element of a 2D array is at [arr.length - 1][arr[0].length - 1].
Common Mistake 2 · Swapping the Row and Column

In grid[r][c] the row always comes first. Writing grid[c][r] reads the wrong element, or throws an exception when there are more columns than rows. When translating from a picture, find the row first.

5Working With a Whole Row

A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index. seats[1] is row 1, an int[]; it has its own length and can be passed to any method that takes a 1D array.

The row expression gives a reference to the row stored in the 2D array, not a copy. Storing it in a variable such as int[] back = seats[1]; creates an alias: changing back[0] changes seats[1][0]. This is useful when a method should process one row, and surprising when a separate copy was intended.

Worked Example 7 Accessing a row

A Row Is a 1D Array

Predict the output.

Code
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
int[] back = seats[1];
System.out.println(back.length);
System.out.println(back[2]);
back[0] = 8;
System.out.println(seats[1][0]);
Output
3
5
8
  1. 1seats[1], with one set of brackets, is row 1: an int[] of length 3.
  2. 2back[2] is the same element as seats[1][2]: 5.
  3. 3Not a copy. back refers to the same row object, so back[0] = 8 changes seats[1][0].
Result: The output is 3, 5, and 8. A single row of a 2D array is accessed with one set of brackets containing the row index, and it is a reference to the row itself.
Common Mistake 3 · Expecting a Row Variable to Be a Copy

After int[] back = seats[1];, both names refer to the same row. Any change made through back appears in seats. To keep the original unchanged, copy the values into a new array element by element.

6Sizes and Valid Indices

The number of rows contained in a 2D array can be accessed through the length attribute. The valid row index values are 0 through one less than the number of rows, inclusive. The number of columns can be accessed through the length attribute of one of the rows, and the valid column index values are 0 through one less than the number of columns, inclusive. For a 2D array named values, the number of rows is values.length and the number of columns is values[0].length.

Using an index value outside of these ranges results in an ArrayIndexOutOfBoundsException. Computing positions from the lengths, such as values.length - 1 for the last row, keeps code correct when the size of the table changes.

Figure 4. The number of rows is arr.length; the number of columns is the length of one row, arr[0].length.
ExpressionMeaningFor grid = new int[3][4]
grid.lengthNumber of rows3
grid[0].lengthNumber of columns (length of a row)4
grid[r]Row r, an int[]Valid for r = 0 to 2
grid[r][c]Element in row r, column cValid for c = 0 to 3
grid[grid.length - 1][grid[0].length - 1]Last elementgrid[2][3]
Worked Example 8 Index errors

One Row Too Far

What happens?

Code
int[][] seats = { {4, 0, 7}, {2, 9, 5} };
System.out.println(seats[1][2]);
System.out.println(seats[2][1]);
  1. 1seats[1][2] is valid: row 1 is the last row and column 2 the last column. It prints 5.
  2. 2seats[2][1] asks for row 2, but valid rows are 0 and 1, so Java throws an ArrayIndexOutOfBoundsException.
Result: The program prints 5 and then stops with an ArrayIndexOutOfBoundsException. Row indices must be less than arr.length, and column indices less than arr[0].length.
Common Mistake 4 · Using length for the Number of Columns

arr.length counts rows, not columns. For a table with 3 rows and 4 columns, arr.length is 3. The number of columns is arr[0].length, the length of a row.

Four Habits for 2D Arrays

1. Row, Then Column

arr[row][col], every time.

2. Two Lengths

arr.length rows; arr[0].length columns.

3. Rows Are Arrays

arr[r] is a 1D array, shared, not copied.

4. Know the Defaults

0, 0.0, false, or null after new.

Core Synthesis

A 2D array is stored as an array of arrays, so the way 2D arrays are created and indexed is similar to 1D array objects. The size of a 2D array is established at the time of creation and cannot be changed, and 2D arrays can store either primitive data or object reference data. When a 2D array is created using the keyword new, its elements are initialized to the default values for their type: 0, 0.0, false, or null. The initializer list for a 2D array consists of initializer lists that represent 1D arrays. The square brackets [row][col] are used to access and modify an element, with the first index for rows and the second for columns. A single row is accessed with one set of brackets containing the row index. The number of rows is arr.length and the number of columns is arr[0].length; an index outside these ranges results in an ArrayIndexOutOfBoundsException.