π8.1: 2D Arrays
Table of Contents
π This page is a condensed version of CSAwesome Topic 8.1
Using a GitHub Template for class notes
- Go to the public template repository for our class: BWL-CS Java Template
- Click the button above the list of files then select
Create a new repository
- Specify the repository name:
CS2-Unit-8-Notes
- Click
Now you have your own personal copy of this starter code that you can always access under the
Your repositories
section of GitHub! - Now on your repository, click and select the
Codespaces
tab - Click
Create Codespace on main
and wait for the environment to load, then youβre ready to code! - π Take notes in this Codespace during class, coding along with the instructor.
Two-Dimensional (2D) Arrays
We have only worked with one-dimensional arrays so far, which have a single row of elements. But in the real world, data is often represented in a two-dimensional table with rows and columns. Programming languages can also represent arrays this way with multiple dimensions. A two-dimensional (2D) array
has rows and columns.
A 2D array in Java is actually an array of 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.
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 nested one-dimensional arrays. The typical way to do this is to store all the data for the first row, with each spot referring to a column, 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.
Java actually stores a two-dimensional array as an array of arrays. Each element of the outer array has a reference to each inner array.
The outer array can be thought of as the rows and the inner arrays as the columns.
The picture above shows a 2D array that has 3 rows and 7 columns. Notice that the array indices start at
0
and end at thelength - 1
.
Declaring 2D Arrays
To declare a 2D array, specify the type
of elements that will be stored in the array, then double brackets ([][]
) to show that it is a 2D array of that type, then at least one space, and then a name
for the array.
int[][] ticketInfo;
String[][] seatingChart;
Note that the declarations above 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).
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]
.
ticketInfo = new int[2][3];
seatingChart = new String[3][2];
The code above creates a 2D array with 2 rows and 3 columns named
ticketInfo
and a 2D array with 3 rows and 2 columns namedseatingChart
.
The total number of elements in a 2D array is the number of rows times the number of columns.
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 set a value in a 2D array, you can use assignment statements with the name
of the array followed by the row
index in square brackets followed by the column
index in square brackets, and then an =
followed by a value:
// Initialize the 2D array
int[][] data = new int[2][3];
// Set value of the first item
data[0][0] = 15;
Initializer Lists for 2D Arrays
You can also initialize (set) the values for the array when you first 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 uses an initializer list to create a value-filled 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"} };
π¬ DISCUSS: What is the value at
seatingInfo[2][1]
after the code above executes?
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
indices in square brackets.
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];
The code above will get the
int
value at row index 1 and column index 0 fromticketInfo
. It will also get theString
value at row index 0 and column index 1 fromseatingChart
.
π» In-Class Activity: ASCII Art
βοΈ Summary
-
A 2D array is stored as an array of arrays. And 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];
-
For the purposes of the exam, when accessing the element at
arr[first][second]
, thefirst
index is used for rows, thesecond
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} };
- For example,
-
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.
π When class ends, donβt forget to SAVE YOUR WORK!
- Navigate to the
Source Control
menu on the LEFT sidebar - Type a brief commit message in the box, for example:
updated Main.java
- Click the button on the LEFT menu
- Click the button on the LEFT menu
- Finally you can close your Codespace!
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.