01 / 20

2D Arrays
in Java

Master grid and matrix data using two-dimensional arrays: declaration, initialization, traversal, and real-world applications.

AP Computer Science A 2D Arrays

What Is a 2D Array?

A 2D array is an array of arrays: a data structure that organizes elements into rows and columns, forming a grid or matrix. Each element is accessed using two indices: one for the row, one for the column.

col 0 col 1 col 2 row 0 row 1 row 2 [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2]

Why Use 2D Arrays?

Any data that is naturally organized in a grid pattern is a perfect candidate for a 2D array. They let you model real-world tables efficiently.

Game Boards
Chess, tic-tac-toe, minesweeper: each cell stores a piece or state.
Image Pixels
Digital images are grids of pixel color values arranged in rows and columns.
Spreadsheets
Gradebooks, schedules, and data tables map perfectly to \( \text{rows} \times \text{cols} \).

Under the Hood: Array of Arrays

In Java, a 2D array is not a single contiguous block. It is an array of references, where each reference points to a separate 1D array (row). This means rows can even have different lengths (jagged arrays).

arr[0] arr[1] arr[2] 1 2 3 4 5 6 7 8 9 int[] (length 3) int[] (length 3) int[] (length 3)

Declaring a 2D Array

There are three main ways to create a 2D array in Java:

1
Declare with size: Creates a \( 3 \times 4 \) grid, filled with default values (0 for int).
2
Literal initialization: Supply all values in nested curly braces.
3
Jagged array: Create only the outer array, then allocate each row separately.
// Method 1: declare with size int[][] grid = new int[3][4]; // Method 2: literal initialization int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Method 3: jagged array int[][] jagged = new int[3][]; jagged[0] = new int[2]; jagged[1] = new int[4]; jagged[2] = new int[3];

Accessing Elements

Use two indices: arr[row][col]. The row index selects which inner array, and the column index selects the element within that array.

int[][] m = { {10, 20, 30}, {40, 50, 60} }; // Read: row 1, col 2 → 60 int val = m[1][2]; // Write: set row 0, col 1 to 99 m[0][1] = 99; // Number of rows int rows = m.length; // 2 // Number of cols in row 0 int cols = m[0].length; // 3

Traversing with Nested Loops

To visit every element, use a nested for loop: the outer loop iterates over rows, the inner loop iterates over columns within each row.

for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[r].length; c++) { System.out.print(grid[r][c] + " "); } System.out.println(); }

Row-Major vs Column-Major

The order you traverse matters for performance and for certain algorithms. Java 2D arrays are stored in row-major order.

Row-Major
Outer loop = rows, inner loop = cols. Reads memory sequentially. Faster in Java due to cache locality.
Column-Major
Outer loop = cols, inner loop = rows. Jumps across rows. Useful when you need to process data column by column.
// Row-major (standard) for (int r = 0; r < rows; r++) for (int c = 0; c < cols; c++) process(arr[r][c]); // Column-major for (int c = 0; c < cols; c++) for (int r = 0; r < rows; r++) process(arr[r][c]);

Enhanced For-Each Loop

Java's enhanced for loop works beautifully with 2D arrays. The outer loop yields each row (a 1D array), and the inner loop yields each element in that row.

for (int[] row : grid) { for (int val : row) { System.out.print(val + " "); } System.out.println(); }

How to Apply 2D Arrays

1
Identify the grid structure: Determine the number of rows and columns your problem requires.
2
Declare and initialize: Use new type[rows][cols] or literal { {...}, {...} } syntax.
3
Populate the array: Use nested loops to assign values based on input or computation.
4
Process with nested loops: Choose row-major or column-major traversal depending on your task.
5
Use .length carefully: Always use arr.length for rows and arr[i].length for columns in that specific row.

Example 1: Sum All Elements

Given a \( 2 \times 3 \) array, compute the sum of every element.

int[][] data = { {3, 7, 1}, {4, 2, 8} }; int sum = 0; for (int r = 0; r < data.length; r++) { for (int c = 0; c < data[r].length; c++) { sum += data[r][c]; } } System.out.println(sum); // 25

Example 2: Max per Row

Find the largest value in each row of a 2D array.

int[][] scores = { {85, 92, 78}, {90, 88, 95}, {70, 82, 81} }; for (int r = 0; r < scores.length; r++) { int max = scores[r][0]; for (int c = 1; c < scores[r].length; c++) { if (scores[r][c] > max) { max = scores[r][c]; } } System.out.println("Row " + r + " max: " + max); }

Example 3: Tic-Tac-Toe Board

Model a tic-tac-toe board as a \( 3 \times 3 \) char array and check if a row has a winner.

char[][] board = { {'X', 'O', 'X'}, {'O', 'O', 'O'}, {'X', ' ', 'X'} }; for (int r = 0; r < 3; r++) { if (board[r][0] == board[r][1] && board[r][1] == board[r][2] && board[r][0] != ' ') { System.out.println( "Row " + r + " winner: " + board[r][0]); } }
X O X O O O X - X

Common Mistakes

✕ Swapping Row/Col
Writing arr[col][row] instead of arr[row][col]. Row always comes first in Java.
✕ Wrong .length
Using arr.length for columns or arr[0].length for rows. They are not interchangeable.
✕ Off-by-One
Accessing arr[arr.length] causes an ArrayIndexOutOfBoundsException. Valid indices are \( 0 \) to \( \text{length} - 1 \).
✕ Null Rows
After new int[3][], each row is null until you allocate it. Accessing a null row throws NullPointerException.

1D vs 2D Arrays

1D Array 2D Array
Declaration int[] arr int[][] arr
Indices arr[i] arr[r][c]
Size arr.length arr.length (rows), arr[i].length (cols)
Traversal Single loop Nested loops (2 levels)
Use case Lists, sequences Grids, matrices, tables
Default values 0 (int), null (Object) Same per element

Question 1 of 5

Given int[][] m = new int[4][6];
what does m.length return?

Question 2 of 5

What is the value of arr[1][2] given:
int[][] arr = {{5, 10, 15}, {20, 25, 30}};

Question 3 of 5

Which code correctly prints every element of a 2D array grid?

Question 4 of 5

After executing int[][] j = new int[3][];
what is the value of j[0]?

Question 5 of 5

What is the total number of elements in an array declared as int[][] a = new int[5][3];?