Fiveable

💻AP Computer Science A Unit 4 Review

QR code for AP Computer Science A practice questions

4.11 2D Arrays

4.11 2D Arrays

Written by the Fiveable Content Team • Last updated June 2026
Verified for the 2027 exam
Verified for the 2027 examWritten by the Fiveable Content Team • Last updated June 2026
💻AP Computer Science A
Unit & Topic Study Guides

Frequently Asked Questions

Previous Exam Prep

Study Tools

Exam Skills

AP Cram Sessions 2021

Pep mascot

What are 2D arrays in AP Computer Science A?

A 2D array in Java is an array of arrays, so you use two indices to reach any element: arr[row][col]. You set the size when you create it and it cannot change, every empty slot starts at the default value for its type, and you get the row count with arr.length and the column count with arr[0].length.

Why This Matters for the AP Computer Science A Exam

2D arrays are the data structure behind tables, grids, and game boards, and Unit 4 (Data Collections) is the heaviest unit on the exam. Getting comfortable with how a 2D array is built and indexed sets you up for the traversal and algorithm work that comes next.

You will see 2D arrays in two main ways:

  • Multiple-choice questions that ask you to trace code, find what prints, or spot why a segment throws an ArrayIndexOutOfBoundsException.
  • Free-response code writing where you write a method that accesses or changes data in a 2D array based on a given scenario and its classes.

For the purposes of the exam, only rectangular 2D arrays are tested. Jagged (nonrectangular) arrays are outside the scope of the course.

Key Takeaways

  • A 2D array is stored as an array of arrays, so its size is fixed at creation and cannot be resized.
  • new initializes every element to a default: 0 for int, 0.0 for double, false for boolean, and null for a reference type.
  • Use arr[row][col] to read or change an element. The first index is the row, the second is the column.
  • arr.length is the number of rows; arr[0].length is the number of columns.
  • An initializer list is made of inner lists that each represent one row, like int[][] arr2D = {{1, 2, 3}, {4, 5, 6}};.
  • Indices outside the valid range throw an ArrayIndexOutOfBoundsException.

Understanding 2D Array Structure

A 2D array is an array where each element is itself an array. That is why you need two indices: one to pick the row, and one to pick the column within that row. The size is set when you create it and cannot change afterward.

</>Java
// Creating a 2D array - this creates a 3x4 grid (3 rows, 4 columns)

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

// What this actually creates in memory:
// Row 0: [0, 0, 0, 0]
// Row 1: [0, 0, 0, 0]
// Row 2: [0, 0, 0, 0]

The first bracket [3] is the number of rows, and the second bracket [4] is the number of columns in each row. Because this is an int array created with new, every slot starts at 0. A double[][] would start at 0.0, a boolean[][] at false, and a reference type like String[][] at null.

2D arrays can hold either primitive values or object references, just like 1D arrays. Here is a String[][] used as a seating chart:

</>Java
public class Array2DVisualization {
    public static void demonstrate2DStructure() {
        // Create a 2D array to represent a classroom seating chart
        String[][] classroom = new String[3][4];

        // Fill it with student names
        classroom[0][0] = "Alice";   classroom[0][1] = "Bob";
        classroom[0][2] = "Carol";   classroom[0][3] = "Dave";

        classroom[1][0] = "Eve";     classroom[1][1] = "Frank";
        classroom[1][2] = "Grace";   classroom[1][3] = "Henry";

        classroom[2][0] = "Ivy";     classroom[2][1] = "Jack";
        classroom[2][2] = "Kate";    classroom[2][3] = "Liam";

        System.out.println("Classroom seating chart:");
        System.out.println("Row 0: " + classroom[0][0] + " " + classroom[0][1] +
                          " " + classroom[0][2] + " " + classroom[0][3]);
        System.out.println("Row 1: " + classroom[1][0] + " " + classroom[1][1] +
                          " " + classroom[1][2] + " " + classroom[1][3]);
        System.out.println("Row 2: " + classroom[2][0] + " " + classroom[2][1] +
                          " " + classroom[2][2] + " " + classroom[2][3]);
    }
}

Creating and Initializing 2D Arrays

There are a few ways to build a 2D array. Pick the one that fits what you know about the data.

Method 1: Declare the size first, then assign values

</>Java
// Create a 2D array with specified dimensions
int[][] scores = new int[3][4];  // 3 rows, 4 columns

// Assign values one by one
scores[0][0] = 85;  scores[0][1] = 92;  scores[0][2] = 78;  scores[0][3] = 91;
scores[1][0] = 88;  scores[1][1] = 76;  scores[1][2] = 94;  scores[1][3] = 82;
scores[2][0] = 90;  scores[2][1] = 87;  scores[2][2] = 85;  scores[2][3] = 89;

Method 2: Use an initializer list at creation

An initializer list for a 2D array is a list of inner lists, where each inner list is one row.

</>Java
// Initialize 2D array with literal values
int[][] scores = {
    {85, 92, 78, 91},  // Row 0
    {88, 76, 94, 82},  // Row 1
    {90, 87, 85, 89}   // Row 2
};

// This is much cleaner and shows the structure clearly

Method 3: Fill with nested loops

</>Java
public static int[][] createMultiplicationTable(int size) {
    int[][] table = new int[size][size];

    // Fill the table using nested loops
    for (int row = 0; row < size; row++) {
        for (int col = 0; col < size; col++) {
            table[row][col] = (row + 1) * (col + 1);
        }
    }

    return table;
}

// Usage: creates a 5x5 multiplication table
int[][] multTable = createMultiplicationTable(5);

Row First, Then Column

When you write arr[first][second], the first index is the row and the second is the column. Mixing these up is one of the most common 2D array mistakes.

</>Java
public class RowMajorDemo {
    public static void demonstrateAccess() {
        char[][] ticTacToe = {
            {'X', 'O', 'X'},
            {'O', 'X', 'O'},
            {'X', 'X', 'O'}
        };

        // Access pattern: array[row][column]
        System.out.println("Top-left corner: " + ticTacToe[0][0]);     // X
        System.out.println("Top-right corner: " + ticTacToe[0][2]);    // X
        System.out.println("Bottom-left corner: " + ticTacToe[2][0]);  // X
        System.out.println("Center: " + ticTacToe[1][1]);              // X

        // Common mistake: mixing up row and column
        // ticTacToe[column][row] is wrong!
        // Always think: "Which row, then which column in that row"
    }
}

A helpful way to remember it: go to the right row first, then find the right column in that row.

You can also grab an entire row with a single index. Since a 2D array is an array of arrays, arr[1] is the 1D array stored at row 1.

</>Java
int[][] matrix = {
    {1, 2, 3, 4},
    {5, 6, 7, 8}
};

int[] secondRow = matrix[1];   // {5, 6, 7, 8}

Length: Rows vs Columns

This is where a lot of people slip up, but it follows directly from the array-of-arrays structure.

</>Java
public class ArrayLengthDemo {
    public static void explainLengthProperties() {
        int[][] matrix = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12}
        };

        // matrix.length gives you the number of ROWS
        System.out.println("Number of rows: " + matrix.length);  // 3

        // matrix[0].length gives you the number of COLUMNS in row 0
        System.out.println("Number of columns in row 0: " + matrix[0].length);  // 4

        // Since this is a rectangular array, all rows have the same length
        System.out.println("Number of columns in row 1: " + matrix[1].length);  // 4
        System.out.println("Number of columns in row 2: " + matrix[2].length);  // 4

        // General rule: matrix[row].length gives columns in that specific row
    }

    public static void demonstrateWithLoop() {
        int[][] data = new int[4][5];  // 4 rows, 5 columns

        // Print dimensions using length properties
        System.out.println("Array dimensions: " + data.length + " x " + data[0].length);

        // Fill array with row*column values
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data[row].length; col++) {
                data[row][col] = row * col;
            }
        }

        // Print the filled array
        for (int row = 0; row < data.length; row++) {
            for (int col = 0; col < data[row].length; col++) {
                System.out.print(data[row][col] + "\t");
            }
            System.out.println();  // New line after each row
        }
    }
}

The valid row indices run from 0 to arr.length - 1, and the valid column indices run from 0 to arr[0].length - 1. Step outside either range and you get an ArrayIndexOutOfBoundsException.

A Worked Example: A Game Board Class

This example pulls the ideas together: creating a char[][], initializing it, accessing and changing elements, checking bounds, and using the length properties to traverse.

</>Java
public class GameBoard {
    private char[][] board;
    private int rows;
    private int cols;

    // Constructor creates board of specified size
    public GameBoard(int numRows, int numCols) {
        this.rows = numRows;
        this.cols = numCols;
        this.board = new char[rows][cols];

        // Initialize all positions to empty space
        initializeBoard();
    }

    // Initialize board with empty spaces
    private void initializeBoard() {
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                board[row][col] = '-';  // Empty space marker
            }
        }
    }

    // Place a piece on the board
    public boolean placePiece(int row, int col, char piece) {
        // Validate coordinates
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) {
            System.out.println("Invalid position: (" + row + ", " + col + ")");
            return false;
        }

        // Check if position is already occupied
        if (board[row][col] != '-') {
            System.out.println("Position (" + row + ", " + col + ") is already occupied");
            return false;
        }

        // Place the piece
        board[row][col] = piece;
        System.out.println("Placed " + piece + " at position (" + row + ", " + col + ")");
        return true;
    }

    // Get piece at specific position
    public char getPiece(int row, int col) {
        if (row < 0 || row >= board.length || col < 0 || col >= board[0].length) {
            return '?';  // Invalid position marker
        }
        return board[row][col];
    }

    // Count pieces of a specific type
    public int countPieces(char piece) {
        int count = 0;

        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                if (board[row][col] == piece) {
                    count++;
                }
            }
        }

        return count;
    }

    // Check if board is full
    public boolean isFull() {
        for (int row = 0; row < board.length; row++) {
            for (int col = 0; col < board[row].length; col++) {
                if (board[row][col] == '-') {
                    return false;  // Found empty space
                }
            }
        }
        return true;  // No empty spaces found
    }
}

Notice how every loop uses board.length for rows and board[row].length for columns. That pattern keeps your code working no matter what size the board is.

How to Use This on the AP Computer Science A Exam

Code Tracing

When a multiple-choice question hands you a 2D array and a code segment, draw the grid as a small table on scratch paper. Label rows down the side and columns across the top, then update cells as the code runs. If the array is not given, make a tiny one of your own (like a 2x3) and trace the code against it to see what the pattern does.

Free Response

For free-response code writing that involves a 2D array, you usually write one method that accesses or changes data in the array. Before coding:

  • Read whether you need every element, just one row, just one column, or some subsection.
  • Use arr.length for the number of rows and arr[r].length for the number of columns so your loops fit any size.
  • Keep [row][col] order consistent so you do not accidentally swap dimensions.

Common Trap

Watch the boundaries. A loop condition of col <= arr[0].length runs one step too far and throws an ArrayIndexOutOfBoundsException. Valid indices stop at length - 1.

Common Misconceptions

  • arr.length is not the total number of elements. It is the number of rows. To get the column count, use arr[0].length. The total element count is rows times columns.
  • Row comes first, not column. arr[2][0] means row 2, column 0. Writing the column index first gives you the wrong element or an exception.
  • You cannot resize a 2D array. Its dimensions are locked in when you create it. To "grow" it, you would create a new larger array and copy values over.
  • new does not leave slots empty or garbage. Every element starts at the type's default: 0, 0.0, false, or null. A String[][] is full of null, not empty strings.
  • For this course, 2D arrays are rectangular. Every row has the same number of columns, so arr[0].length reliably gives the column count. Jagged arrays are outside the scope of the exam.
  • An out-of-range index throws an exception at run time. It does not quietly wrap around or return a default. Using an index below 0 or at/above the length triggers an ArrayIndexOutOfBoundsException.

Vocabulary

The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.

Term

Definition

2D array

A two-dimensional data structure consisting of rows and columns used to store and organize data in a grid format.

ArrayIndexOutOfBoundsException

An error that occurs when attempting to access an array element using an index value outside the valid range of 0 through length minus one.

arrays of arrays

A data structure where a 2D array is implemented as an array where each element is itself a 1D array.

column index

The second index in the square brackets [row][col] notation used to specify which column of a 2D array to access.

default values

The initial values automatically assigned to instance variables by the default constructor based on their data type (0 for int, 0.0 for double, false for boolean, null for reference types).

initializer list

A syntax used to create and initialize an array with specific values at the time of creation.

length attribute

A property of an array that indicates the number of elements it contains and cannot be changed after creation.

object reference data

Data types that store references to objects rather than primitive values.

primitive data

Basic data types in Java such as int, double, and boolean that store values directly.

row index

The first index in the square brackets [row][col] notation used to specify which row of a 2D array to access.

Frequently Asked Questions

What is a 2D array in AP Computer Science A?

A 2D array in Java is an array of arrays. On the AP CSA exam, you use it to store rectangular collections of related data, such as grids, tables, and boards.

How do you create a 2D array in Java?

You can create a 2D array with new, such as int[][] grid = new int[3][4], or with an initializer list, such as int[][] nums = {{1, 2}, {3, 4}}.

How do row and column indexes work in a 2D array?

Use arr[row][col]. The first index selects the row, and the second index selects the column in that row. AP CSA treats the first index as rows and the second as columns.

What are the default values in a new 2D array?

A 2D array created with new starts with default values: 0 for int, 0.0 for double, false for boolean, and null for reference types such as String.

How do you find rows and columns in a 2D array?

arr.length gives the number of rows. For rectangular arrays, arr[0].length gives the number of columns. Valid indexes stop at length - 1.

What 2D array mistakes cause ArrayIndexOutOfBoundsException?

Common mistakes include using <= instead of < in loop conditions, swapping row and column indexes, or trying to access an index equal to the length. Java indexes start at 0 and end at length - 1.

Pep mascot
Upgrade your Fiveable account to print any study guide

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Click below to go to billing portal → update your plan → choose Yearly→ and select "Fiveable Share Plan". Only pay the difference

Plan is open to all students, teachers, parents, etc
Pep mascot
Upgrade your Fiveable account to export vocabulary

Download study guides as beautiful PDFs See example

Print or share PDFs with your students

Always prints our latest, updated content

Mark up and annotate as you study

Plan is open to all students, teachers, parents, etc
report an error
description

screenshots help us find and fix the issue faster (optional)

add screenshot