Search⌘ K
AI Features

Two Dimensional (2D) Arrays

Explore how two dimensional arrays work in Java including their row and column structure, creation, and value assignment. Understand these concepts to solve array problems effectively and prepare for the AP Computer Science A exam.

Introduction

The concept of two-dimensional arrays is built on the arrays (one-dimensional array). Remember: when we talked about arrays in real life, we referred to them as lockers. Well, the same can be done for 2D-arrays. Look at the image below.

Picture a 2D array as the combination of both rows and columns of small lockers. A row has horizontal elements. A column has vertical elements. In the picture above, there are two rows and four columns of lockers. In this case, to locate a locker, you address it as a locker in 1st row, 2nd column. You have to provide both the row and column number.

2D arrays in Java

Java stores 2D arrays as arrays of arrays. Each element of the outer array stores a reference to an inner array. Look at the figure below.

The picture above shows a 2D array that has two rows and four columns. Notice that the array indices start at 00 and end at the length - 1.

Note: It is possible, in Java, to have inner arrays of different lengths, but on the AP CS A exam, all inner arrays will have the same length.

Creating a 2D array

In the case of a 2D array, we have two entities: rows and columns. So, instead of one [], we’ll use [] two times. Look at the code below.

Java
class Create2DArray
{
public static void main(String args[])
{
// Creating 2D arrays
int[][] array1 = new int[2][4];
int[][] array2;
array2 = new int[3][2];
}
}

Look at line 6. Let’s go through it:

  • int: Type of the values you want in a 2D array
  • [][]: Double square brackets right after the type.
  • array1: Name of the 2D array variable

new int[2][4] means a 2D array is created having two rows and four columns.

Look at line 8. We declare another 2D array: array2. However, this doesn’t create a 2D array. At line 9, new int[3][2] actually creates the 2D array having three rows and two columns.

Remember: the first index is used for rows, and the second is used for columns.

Assigning values to a 2D array

Look at the code below.

Java
class ArrayWithValues
{
public static void main(String args[])
{
// Creating 2D array with values
int[][] array1 = {{1, 2}, {3, 4}, {5, 6}};
System.out.println(array1[2][1]);
}
}

Look at line 6. We create a 2D array with values. Let’s go through it:

  • {{1, 2}}: First row added with two columns in it
  • {{3, 4}}: Second row added with two columns in it
  • {{5, 6}}: Third row added with two columns in it

As we stated above, it is possible to have inner arrays of variable length, but, according to the scope of AP CS A, we are keeping a constant number of columns. Now, look at line 7. We print the value in the 33rd row and 22nd column, i.e. 66.