2D - 2D Arrays (Lesson)

APCompSci_LessonTopBanner.png

2D Arrays

Introduction

Instead of data just being linear as with arrays or ArrayLists, two-dimensional arrays allow us to store data in a matrix format. A 2D array is an array of arrays. Data that is shown in a table is most suitable for storing in a 2D array. Each element can be accessed using the variable name with row and column indices.

Creating a 2D Array

To create a 2D array, you need to specify how many rows and columns you need. The first square brackets are used for the number of rows and the second square brackets are used for the number of columns.

type[][] identifier = new type[numRow][numCol];

For example:

int row = 3;
int col = 3;

String [ ] [ ] ticTacToe = new String [row] [col];

This will create a 2D array with 9 elements:

ticTacToe[0][0] ticTacToe[0][1] ticTacToe[0][2]
ticTacToe[1][0] ticTacToe[1][1] ticTacToe[1][2]
ticTacToe[2][0] ticTacToe[2][1] ticTacToe[2][2]

Accessing Elements in a 2D Array

To access an element, use two index values in separate square brackets:

ticTacToe [1] [1] = "x";
ticTacToe [1] [0] = "o"; 

What will ticTacToe look like after these elements are initialized?

tictactoe1_2DArrays.png 

Answer:

tictactoe2_2DArrays.png 

2D arrays can also be initialized with a list. The initializer list used to create and initialize a 2D array consists of initializer lists that represent arrays. 

String [ ] [ ] schedule = { { "Period1", "Period2", "Period3"}, 
{"Math", "Comp Sci", "Language Arts" } }; 

Period1 Period2 Period3
Math Comp Sci Language Arts

 

 

Duck saying "Only rectangular 2D arrays will be on the AP Exam."

Book Icon Click on "Runestone Academy" below to open the required reading that is listed.

Runestone Academy: AP CSA – Java Review Links to an external site.:

READ: 10 – Two-dimensional Arrays

Book Icon Click on "Introduction to Computer Science Using Java" below to open the required reading that is listed.

Introduction to Computer Science Using Java Links to an external site.:

READ: Chapter 67: Two Dimensional Arrays

Secret Code

Click below to complete the Secret Code Activity.

 

 

APCompSci_LessonBottomBanner.pngIMAGES CREATED BY GAVS