## AP Computer Science :: Lessons :: 2D Arrays

### 2D Arrays

A two-dimensional array, also known as a matrix, is simply an array that holds arrays. It is used quite often for tables of values (such as the cells in Excel), mazes, and games based on grids. Other multi-dimensional arrays can be used, but the increase in memory can be dramatic so normally nothing past 3D arrays is used.

1 6 1 8 0 3 3 9 8 8 7 4

The above numbers make up a 3 x 4 rectangular matrix. A rectangular matrix is one in which each row has the same number of elements. We will only deal with rectangular matrices in AP Computer Science, but it is possible to create a jagged array that does not have the same number of elements in each row. There are a number of ways you can create the above matrix in Java. The first is by declaring the array and using an initializer list to set the values.

int[][] matrix = { {1, 6, 1, 8}, {0, 3, 3, 9}, {8, 8, 7, 4} };

The two pairs of square brackets indicate that this is a 2D array. Each set of curly brackets indicates a new row in the matrix. The initialization above would create the rectangular matrix we saw earlier. The example below will create the same matrix, but the array is not populated on the same line where it is declaorangeBold.

int[][] matrix = new int[3][4]; matrix[0][0] = 1; matrix[0][1] = 6; matrix[0][2] = 1; matrix[0][3] = 8; matrix[1][0] = 0; matrix[1][1] = 3; matrix[1][2] = 3; matrix[1][3] = 0; matrix[2][0] = 8; matrix[2][1] = 8; matrix[2][2] = 7; matrix[2][3] = 4;

A 2D array element is accessed by specifying the row followed by the column. It is important that you remember the column is specified after the row.