2D - 2D Arrays (Lesson)
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:
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:
What will ticTacToe look like after these elements are initialized?
Answer:
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.
Period1 | Period2 | Period3 |
Math | Comp Sci | Language Arts |
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
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.
IMAGES CREATED BY GAVS