Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

8.1: 2D Array Basics

A 2D Java array is an array of rows. grid.length counts rows, and grid[r].length counts elements in a particular row.

College Board Unit 4

How it works

A 2D array in Java is an array of arrays, stored in row-major order, so grid[r][c] means row r, column c. The number of rows is grid.length and the number of columns in a row is grid[r].length. Creating one with new int[3][4] gives three rows of four columns, all filled with the type default. Initializer lists let you write the grid out literally, with each inner set of braces forming one row.

Use the outer length for the row count and each row’s own length for its column count.

Common error

Assuming every row has the same length, which fails on a ragged array.

Worked example

Java

int[][] grid = {{2,4,6},{1,3,5}};
System.out.println(grid.length + ":" + grid[0].length);
System.out.println(grid[1][2]);

Output

2:3
5

There are two rows and three elements in each row. The final access selects row 1, column 2.

Exercises

8.1.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

int[][] grid = new int[2][3];
grid[1][0] = 7;
System.out.println(grid[0][1] + grid[1][0]);
Show solution

Output

7

All elements begin at 0; only row 1, column 0 is assigned 7.

8.1.2 · Write code

Create a 3 by 3 int array with 1 on its main diagonal and 0 elsewhere. Print each row with Arrays.toString.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

int[][] identity = new int[3][3];
for (int i = 0; i < identity.length; i++) identity[i][i] = 1;
for (int[] row : identity) System.out.println(Arrays.toString(row));
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic