2D Arrays

Arrays in Java can store many items of the same type. You can even store items in two-dimensional (2D) arrays which are arrays that have both rows and columns. A row has horizontal elements. A column has vertical elements. In the picture below there are 3 rows of lockers and 6 columns.

../_images/2DLockers.jpg

Figure 1: Lockers in rows and columns

Two dimensional arrays are especially useful when the data is naturally organized in rows and columns like in a spreadsheet, bingo, battleship, theater seats, classroom seats, or a picture. In battleship, letters map to the rows (A is the first row, B is the second row, and so on) and the column indices start with 1.

Array Storage

Many programming languages actually store two-dimensional array data in a one-dimensional array. The typical way to do this is to store all the data for the first row followed by all the data for the second row and so on. This is called row-major order. Some languages store all the data for the first column followed by all the data for the second column and so on. This called column-major order.

../_images/rowMajor.png

Figure 1: A 2D array stored in row-major order or column-major order as a 1D array.

How Java Stores 2D Arrays

Java actually stores two-dimensional arrays as arrays of arrays. Each element of the outer array has a reference to each inner array. The picture below shows a 2D array that has 3 rows and 7 columns. Notice that the array indices start at 0 and end at the length - 1.

../_images/ArrayRowsAndCols.png

Figure 3: Java arrays of arrays

On the exam assume that any 2 dimensional (2D) array is in row-major order. The outer array can be thought of as the rows and the inner arrays the columns.

exercise Check your understanding

Try to answer the following questions. Click on the value or values to select them. Click again to unselect a value.

Declaring 2D Arrays

To declare a 2D array, specify the type of elements that will be stored in the array, then ([][]) to show that it is a 2D array of that type, then at least one space, and then a name for the array. Note that the declarations below just name the variable and say what type of array it will reference. The declarations do not create the array. Arrays are objects in Java, so any variable that declares an array holds a reference to an object. If the array hasn’t been created yet and you try to print the value of the variable, it will print null (meaning it doesn’t reference any object yet). Try the the following in DrJava’s interaction pane.

int[][] ticketInfo;
String[][] seatingChart;

exercise Check your understanding

To create an array use the new keyword, followed by a space, then the type, and then the number of rows in square brackets followed by the number of columns in square brackets, like this new int[numRows][numCols].

The code below creates a 2D array with 2 rows and 3 columns named ticketInfo and a 2D array with 3 rows and 2 columns named seatingChart. The number of elements in a 2D array is the number of rows times the number of columns.

ticketInfo = new int [2][3];
seatingChart = new String [3][2];

exercise Check your understanding

coding exercise Coding Exercise

What will the TicketInfo program 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 in the next lesson.

Set Value(s) in a 2D Array

When arrays are created their contents are automatically initialized to 0 for numeric types, null for object references, and false for type boolean. To explicitly put a value in an array, you can use assignment statements with the name of the array followed by the row index in brackets followed by the column index in brackets and then an = followed by a value.

int[][] ticketInfo = new int[2][3];
ticketInfo[0][0] = 15;

coding exercise Coding Exercise

Try the TwoDArraySet program. Did it print what you expected? When you print a two dimensional array you just get the reference to the object. In the next lesson, we’ll learn how to use nested loops to print out the whole 2D Array. Right now, use the debugger to see what the values are after this code runs. Edit the code to add in an extra row to the seatingChart and add your name and a friend’s name in the columns of this extra row using assignment statements.

Add another row of data to the arrays by changing the size of the arrays and adding in the assignment statements for the cells in those rows. Use the debugger to see the contents of the array.

exercise Check your understanding

Initializer Lists for 2D Arrays

You can also initialize (set) the values for the array when you create it. In this case you don’t need to specify the size of the array, it will be determined from the values you give. The code below creates an array called ticketInfo with 2 rows and 3 columns. It also creates an array called seatingInfo with 3 rows and 2 columns.

int[][] ticketInfo = { {25,20,25}, {25,20,25} };
String[][] seatingInfo = { {"Jamal", "Maria"}, {"Jake", "Suzy"}, {"Emma", "Luke"} };

exercise Check your understanding

Get a Value from a 2D Array

To get the value in a 2D array give the name of the array followed by the row and column indicies in square brackets. The code below will get the value at row index 1 and column index 0 from ticketInfo. It will also get the value at row index 0 and column index 1 from seatingChart.

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];

exercise Check your understanding

coding exercise Coding Exercise

Open the TwoDArrayInitGet program. 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.

Summary

  • 2D arrays are stored as arrays of arrays. Therefore, the way 2D arrays are created and indexed is similar to 1D array objects.

  • 2D arrays are declared and created with the following syntax: datatype[][] variableName = new datatype[numberRows][numberCols];

  • When accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.

  • The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays. For example, int[][] ticketInfo = { {25,20,25}, {25,20,25} };

  • The square brackets [row][col] are used to access and modify an element in a 2D array.

  • “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.

You have attempted of activities on this page