4.11 - 2D Array Creation and Access

superdancer16

Introduction

So far we've worked with one-dimensional arrays—single rows of data. But many real-world problems require grid-like data: spreadsheets, game boards, images, seating charts, and matrices. Two-dimensional (2D) arrays store data in rows and columns, like a table.

Topic 4.11 introduces creating and accessing 2D arrays. Understanding 2D array structure is essential—they appear on the AP exam's 2D array free-response question (Question 4) and in multiple-choice problems.

What is a 2D Array?

A 2D array is stored as an array of arrays. Think of it as an array where each element is itself an array.

Visual representation:

This 2D array has 3 rows and 3 columns.

Therefore, the way 2D arrays are created and indexed is similar to 1D array objects. The outer array holds rows; each row is a 1D array holding column values.

Creating 2D Arrays

The size of a 2D array is established at the time of creation and cannot be changed. Like 1D arrays, 2D arrays have fixed dimensions.

Using the new Keyword

int[][] grid = new int[3][4];

This creates a 2D array with:

  • 3 rows (indices 0-2)
  • 4 columns (indices 0-3)
  • All elements initialized to 0 (default for int)

Syntax breakdown:

  • int[][] — declares a 2D array of integers
  • grid — variable name
  • new int[3][4] — creates 3×4 array

2D arrays can store either primitive data or object reference data.

Examples:

double[][] temperatures = new double[7][24];  // 7 days × 24 hours
String[][] seatingChart = new String[5][6];   // 5 rows × 6 seats
boolean[][] gameBoard = new boolean[8][8];    // 8×8 chess board

Default Initialization

When a 2D array is created using the keyword new, all of its elements are initialized to the default values for the element data type:

  • int: 0
  • double: 0.0
  • boolean: false
  • Reference types: null
int[][] numbers = new int[2][3];
// All elements are 0:
// [[0, 0, 0],
//  [0, 0, 0]]
String[][] names = new String[2][2];
// All elements are null:
// [[null, null],
//  [null, null]]

Using Initializer Lists

The initializer list used to create and initialize a 2D array consists of initializer lists that represent 1D arrays.

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

This creates a 3×3 array where:

  • Row 0: [1, 2, 3]
  • Row 1: [4, 5, 6]
  • Row 2: [7, 8, 9]

Compact form:

int[][] arr = {{1, 2}, {3, 4}, {5, 6}};
// 3 rows × 2 columns

Accessing Elements

The square brackets [row][col] are used to access and modify an element in a 2D array.

For the purposes of the exam, when accessing the element at arr[first][second], the first index is used for rows, the second index is used for columns.

int[][] grid = {
    {10, 20, 30},
    {40, 50, 60}
};

System.out.println(grid[0][0]);  // 10 (row 0, col 0)
System.out.println(grid[0][2]);  // 30 (row 0, col 2)
System.out.println(grid[1][1]);  // 50 (row 1, col 1)

Modifying elements:

grid[0][0] = 99;  // Change 10 to 99
grid[1][2] = 88;  // Change 60 to 88
// grid is now:
// [[99, 20, 30],
//  [40, 50, 88]]

Accessing Entire Rows

A single array that is a row of a 2D array can be accessed using the 2D array name and a single set of square brackets containing the row index.

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

int[] row1 = matrix[1];  // Gets second row: [4, 5, 6]
System.out.println(row1[0]);  // 4
System.out.println(row1[1]);  // 5
System.out.println(row1[2]);  // 6

This is useful for processing one row at a time:

for (int i = 0; i < matrix[0].length; i++) 
{
    System.out.print(matrix[0][i] + " ");  // Print first row
}
// Output: 1 2 3

Array Dimensions and Length

Number of Rows

The number of rows contained in a 2D array can be accessed through the length attribute.

int[][] grid = new int[5][3];
int numRows = grid.length;  // 5

The valid row index values for a 2D array are 0 through one less than the number of rows or the length of the array, inclusive.

For a 2D array with rows:

  • Valid row indices:

Number of Columns

The number of columns contained in a 2D array can be accessed through the length attribute of one of the rows.

int[][] grid = new int[5][3];
int numCols = grid[0].length;  // 3

The valid column index values for a 2D array are 0 through one less than the number of columns or the length of any given row of the array, inclusive.

For a 2D array with columns:

  • Valid column indices:

Complete Example

int[][] values = {
    {10, 20, 30, 40},
    {50, 60, 70, 80},
    {90, 100, 110, 120}
};

int rows = values.length;        // 3
int cols = values[0].length;     // 4

System.out.println("Dimensions: " + rows + "x" + cols);
// Output: Dimensions: 3x4

Given a 2D array named values, the number of rows is values.length and the number of columns is values[0].length.

ArrayIndexOutOfBoundsException

Using an index value outside of these ranges will result in an ArrayIndexOutOfBoundsException.

int[][] grid = new int[3][4];  // 3 rows, 4 columns

grid[0][0] = 5;   // OK
grid[2][3] = 10;  // OK (last valid position)
grid[3][0] = 15;  // ERROR: row 3 doesn't exist
grid[0][4] = 20;  // ERROR: column 4 doesn't exist
grid[-1][0] = 25; // ERROR: negative index

Common mistakes:

// WRONG - using length as index
int last = grid[grid.length][0];  // Row index out of bounds

// CORRECT - subtract 1
int last = grid[grid.length - 1][0];

Complete Examples

Example 1: Creating and Populating

int[][] scores = new int[3][2];  // 3 students, 2 tests

// Populate with scores
scores[0][0] = 85;  scores[0][1] = 92;
scores[1][0] = 78;  scores[1][1] = 88;
scores[2][0] = 91;  scores[2][1] = 95;

// Access individual scores
System.out.println("Student 0, Test 0: " + scores[0][0]);

Example 2: Using Initializer List

String[][] schedule = {
    {"Math", "English", "Science"},
    {"History", "PE", "Art"},
    {"Music", "Spanish", "Lunch"}
};

System.out.println(schedule[1][2]);  // "Art"
System.out.println("Days: " + schedule.length);        // 3
System.out.println("Periods: " + schedule[0].length);  // 3

Example 3: Processing a Row

int[][] data = {
    {5, 10, 15},
    {20, 25, 30},
    {35, 40, 45}
};

// Calculate sum of second row
int[] row2 = data[1];
int sum = 0;
for (int val : row2) {
    sum += val;
}
System.out.println("Row 2 sum: " + sum);  // 75

Practice Problems