Section 6.4 Two-dimensional arrays
The arrays weβve been dealing with so far are also called, more specifically, one-dimensional arrays because the elements are arranged along a one dimension like numbers on the number line or people on line to get a cinnamon bun or slice of pizza thatβs gone viral on TikTok. In order to indicate which element we want out of a one-dimensional array we need just one number, the index.
But sometimes itβs useful to think of data arranged in more than one dimension. For instance many things are arranged in horizontal rows and vertical columns like spreadsheets, chess boards, bingo cards, and theater seats. And all the images on a computer screen are ultimately made up of tiny pixels arranged into a two-dimensional arrangement of rows and columns. In the picture below there are three rows of lockers and six columns.

In Java we can also make two-dimensional arrays or 2d arrays which can be indexed with two indices which we can think of as rows and columns or x and y. Though as it turns out, Javaβs 2d arrays are really just 1d arrays that happen to contain 1d arrays as their elements. So if we fully understand how arrays work in general, thereβs not much more to learn about 2d arrays.
Subsection 6.4.1 Declaring 2d arrays
The key to understanding 2d arrays is to understanding that 1d arrays can contain any kind of value, which includes other arrays. So, to review, if we want to make an array of
int
values, we use int[]
. And for an array of String
values we use String[]
.
Which means if we want to make an array whose values are
int[]
, that is, one-dimensional arrays, we use int[][]
, adding another pair of square brackets []
after the element type. Thus we can think of an int[][]
either as a 2d array (which is how we normally think of it) or as a 1d array whose elements are int[]
.
Here are two declarations of 2d array variables:
int[][] ticketInfo;
String[][] seatingChart;
As with any array declarations, declaring a variable doesnβt cause an actual array to be created so these variables will be
null
until they are initialized. And we have no idea how big the arrays will be that these variables will eventually reference.
Subsection 6.4.2 Creating 2d arrays
The array creation expressions and array initializers we used with one-dimensional arrays also work to create 2d arrays. The main difference is that when we want to construct a 2d array of a specific size, we need to specify the size of both dimensions and when we use an array initializer we need use nested
{}
to provide initial values in two dimensions.
For example, hereβs how to create array values of a particular size and assign them to the
ticketInfo
and seatingChart
declared above:
ticketInfo = new int[2][3];
seatingChart = new String[3][2];
Those array creation expressions create an outer array which has the length specified by the number in the first set of
[]
and then creates that many inner arrays whose length is specified in the second set of []
. Typically (and always on the AP exam) we think of the first dimension as rows and the second as columns. So weβd describe ticketInfo
as two rows of three columns each while seatingChart
is three rows of two columns each. Each row of a 2d array is represented by a 1d array containing the actual values in that row and each column.
The values in the inner arrays are filled with the appropriate zero type for their element type,
int
for the inner arrays of ticketInfo
and String
for the inner ararys of seatingChart
. So in total ticketInfo contains six int
zeros arranged into two three-element inner arrays while seatingChart
contains six null
refernces arranged into three two-element inner arrays.
We can also use array initializers to create array values with specific values. We write the inner arrays as array initializers nested within an outer set of
{}
. As with a one-dimensional array initializer we donβt need to specify the dimensions of the array in the []
because itβs implicit in the number of values provided. Here are initializers for our two variables that set them to arrays of the same shape (number of rows and columns) as the previous array creation expressions, though this time with specific, non-zero values in the inner arrays.
// Using array initializer
ticketInfo = new int[][] { { 25, 20, 25 }, { 25, 20, 25 } };
seatingInfo = new String[][] { { "Jamal", "Maria" }, {"Jake", "Suzy" }, { "Emma", "Luke" } };
Also similar to creating 1d arrays we can use array initializers to provide specific values. In this case, the syntactic sugar of not having to include the
new
and the type of the arrays when weβre initializing a newly declared array variable, makes things pretty compact and readable:
int[][] ticketInfo = { { 25, 20, 25}, { 25, 20, 25} };
String[][] seatingInfo = { { "Jamal", "Maria" }, { "Jake", "Suzy" }, { "Emma", "Luke" } };
Note 6.4.2.
There are other ways to create arrays that are outside of the scope of the AP curriculum. For instance, we can make a new array with the second dimension unspecified like
new int[10][]
which will create a ten-element array initialized with null
values that can latter be assigned references to any int[]
. And those arrays donβt necessarily all have be the same length, giving us a non-rectangular array. Similarly with array initializers we can make arbitrarily shaped arrays. But all 2d arrays on the AP exam will be rectangular, meaning every row will be the same length.
Activity 6.4.2.
Activity 6.4.3.
What will the following code print out? Can you change ticketInfo to be an array of 5 rows and 10 columns? Can you declare another array called studentNames that has 10 rows and 5 columns? The length property of arrays will be explained below.
Try to answer the following questions. Click on the value or values to select them. Click again to unselect a value.
Activity 6.4.4.
Activity 6.4.5.
Activity 6.4.6.
Activity 6.4.7.
Activity 6.4.8.
Subsection 6.4.3 Accessing values in a 2d array
Another similarity between one-dimensional and 2d arrays is the way we access the values. Normally we want to get and set the actual values in the array, such as the
int
values in an int[][]
. Just like with a one-dimensional array we use an array access expression, but this time with two pairs of []
rather than just one. The expression in the first pair gives us the index into the outer array, or the row index, and the expression in the second pair gives the column index used to index into the inner array.
Hereβs some code that initializes some arrays and then accesses some values, getting the value from row one, column zero of
ticketInfo
and from row zero, column one of seatingInfo
. It then assigns a new value to row zero, column zero of ticketInfo
:
int[][] ticketInfo = { {25,20,25}, {25,20,25} };
String[][] seatingInfo = { {"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"} };
int value = ticketInfo[1][0];
String name = seatingInfo[0][1];
ticketInfo[0][0] = 15;
Activity 6.4.9.
What is the value of
name
after the code above executes?
- Jamal
- This would be true for if
name
was set toseatingInfo[0][0];
instead. - Maria
- Maria is the value of
seatingInfo[0][1];
. - Jake
- This would be true for if
name
was set toseatingInfo[1][0];
instead. - Suzy
- This would be true for if
name
was set toseatingInfo[1][1];
instead. - Emma
- This would be true for if
name
was set toseatingInfo[2][1];
instead.
Activity 6.4.10.
Try to predict what the code below will print then run it. Did it print what you expected? If it didnβt, open the Hint below for an explanation. After youβve run it once, edit the code to add an extra row to the
seatingChart
array and add your name and a friendβs name in the columns of this extra row using assignment statements.
Hint.
While
System.out.println
can turn any value into a String
to print it, not all reference types to a particularly useful string representation. Arrays, in particular, turn into the gibberish you see when you run this program.
In the next lesson, weβll learn how to use nested loops to print out a whole 2D Array. Right now, you can use the CodeLens button to see what the values are after this code runs. Or you can add this line at the top of the code.
import java.util.Arrays;
and the change the two
System.out.println
lines to:
System.out.println(Arrays.deepToString(ticketInfo));
System.out.println(Arrays.deepToString(seatingChart));
to get more readable representations of the two arrays.
Activity 6.4.11.
Which of the following sets the value for the 3rd row and 2nd column of a 2D array called
nums
?
- nums[3][2] = 5;
- Remember that the indices start at 0.
- nums[1][2] = 5;
- Remember that the row is first then the column.
- nums[2][1] = 5;
- This will set the value of the 3rd row and 2nd column.
- nums[2][3] = 5;
- Remember that the row is first and then the column and that the indices start at 0.
Activity 6.4.12.
Add another row to seatingInfo initialized to your name and a friendβs name. Get these names out of the array using the correct indices and then print them out.
Subsection 6.4.4 2D array sizes
As we know, we can get the length of a one-dimensional aarray using itβs
length
property. That property of course exists on 2d arrays too, because they are just one-dimensional arrays that happen to contain other arrays. So the length
of a 2d array is the number of rows in the array and the length
of any of those rows is the number of columns. Traditionally programmers will use array[0].length
since as long as the array has any rows it has a row 0
.
ticketInfo.length // number of rows
ticketInfo[0].length // number of columns
As always, the length of an array determines what indices are valid. So the valid row indices of a 2d array,
grid
are from 0
to grid.length - 1
, inclusive, and the valid column indices are from 0
to grid[0].length - 1
, also inclusive. Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException
.
Note 6.4.8.
Using the length of the zeroth row as number of columns only works if the array is rectangular, meaning all the rows contain the same number of columns. That will be true of all 2d arrays on the AP exam but is not necessarily true in general.
Activity 6.4.13.
Activity 6.4.14.
Which of the following could be used to get the value in the third row and second column from a 2D array called
nums
?
- nums[3][2]
- This would be true if array indices started with 1 but they start with 0.
- nums[2][3]
- This would be true if array indices started with 1 and the column was specified first. However, array indices start at 0 and the row is given first in row-major order.
- nums[2][1]
- Array indices start with 0 so the third row has an index of 2 and the second column has an index of 1.
- nums[1][2]
- This would be true if the column index was first, but in row-major order the row index is first.
Subsection 6.4.5 Coding Challenge: ASCII art
ASCII is a commonly used character encoding standard where each key you press on the keyboard is translated to an ASCII number to be stored in the computer. ASCII has been mostly replaced by UNICODE which includes characters in other languages like Chinese. In the days before good graphics, some people made ASCII art just using the keyboard characters. Take a look at this ASCII art collection!
We can represent ASCII art in a 2D array of rows and columns. What do you think the following code will print out? Try to guess before you run it. The loops to print out the 2D array will be explained in the next lesson. Then, do the following:
-
Change the code to use 2 assignment statements with the 2D array
asciiArt
to change the βoβ characters to β@β characters. You should figure out what the row and column indices should be for the βoβ characters and use them with the array name to set that character to β@β. After testing this code, comment it out so that your teacher can still see it. -
Add a new
asciiArt
array with a different ASCII art from the collection or of your own design. Be careful with the special characters like"
and\
. You will need to put another backslash in front of these to print them out like\"
and\\
.
Project 6.4.15.
Part 1: Add 2 assignment statements for the 2D array asciiArt to change the βoβ characters to β@β characters. Part 2: Create a new asciiArt array and print it out.
Subsection 6.4.6 Summary
-
(AP 4.11.A.1) A 2D array is stored as an array of arrays. Therefore, 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. 2D arrays can store either primitive data or object reference data. Nonrectangular 2D array objects (with varying column length for each row) are outside the scope of the AP Computer Science A course and exam.
-
2D arrays are declared and created with the following syntax:
datatype[][] variableName = new datatype[numberRows][numberCols]
; -
(AP 4.11.A.2) 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. The default value forint
is0
, fordouble
is0.0
, forboolean
isfalse
, and for a reference type isnull
. -
(AP 4.11.A.3) 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} };
. -
(AP 4.11.A.4) The square brackets
[row][col]
are used to access and modify an element in a 2D array. For the purposes of the AP exam, when accessing the element atarr[first][second]
, thefirst
index is used for rows, thesecond
index is used for columns. -
Row-major order refers to an ordering of 2D array elements where traversal occurs across each row, while column-major order traversal occurs down each column.
-
(AP 4.11.A.5) 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.
-
(AP 4.11.A.6) The number of rows contained in a 2D array can be accessed through the
length
attribute. The valid row index values for a 2D array are0
through one less than the number of rows or the length of the array, inclusive. The number of columns contained in a 2D array can be accessed through thelength
attribute of one of the rows. The valid column index values for a 2D array are0
through one less than the number of columns or the length of any given row of the array, inclusive. For example, given a 2D array namedvalues
, the number of rows isvalues.length
and the number of columns isvalues[0].length`
. Using an index value outside of these ranges will result in anArrayIndexOutOfBoundsException
.
You have attempted of activities on this page.