AP Computer Science A 2D Array — Worked Answer Explanations

Unit 8 · 12 questions explained

Below is a complete answer key for our AP Computer Science A 2D Array practice questions. For each question you'll find the correct choice, a full written explanation of how to get there, and — for every wrong answer — a short note on exactly why it's tempting and where it goes wrong. Reading these straight through is one of the fastest ways to find the gaps in a unit before exam day.

Prefer to test yourself first? Take the timed 2D Array practice test and come back here to review, or head back to the 2D Array unit overview.

In-content ad
  1. Question 1 · Easy

    Consider the following 2D array declaration:

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

    What is the value of arr[1][2]?

    • A
      3
      Why not A: Confused row 0 index 2 (value 3) with row 1 index 2.
    • B
      5
      Why not B: Read arr[1][1] (the center element) instead of arr[1][2].
    • C
      6Correct
    • D
      8
      Why not D: Read arr[2][1] by swapping row and column indices.
    Explanation

    In Java, arr[row][col] uses zero-based indexing. Row 1 is {4, 5, 6} and column index 2 of that row is 6. So arr[1][2] == 6.

    Key takeaway

    arr[r][c] means row r, column c, both zero-indexed.

  2. Question 2 · Easy

    Which declaration correctly creates a 2D array of integers with 4 rows and 3 columns?

    • A
      int[4][3] arr;
      Why not A: Java does not allow sizes inside the brackets on the left side of a declaration.
    • B
      int arr[4][3];
      Why not B: This is C-style syntax; Java requires brackets after the type, not after the variable name.
    • C
      int[][] arr = new int[4][3];Correct
    • D
      int[][] arr = new int[3][4];
      Why not D: Swapped rows and columns; this creates 3 rows and 4 columns.
    Explanation

    In Java, new int[rows][cols] allocates a 2D array with the given number of rows and columns. new int[4][3] produces 4 rows and 3 columns, matching the requirement.

    Key takeaway

    new int[rows][cols]: first dimension is rows, second is columns.

  3. Question 3 · Easy

    Given the following code snippet:

    int[][] grid = new int[3][4];
    System.out.println(grid.length + " " + grid[0].length);
    

    What is printed?

    • A
      4 3
      Why not A: Swapped the meanings of grid.length and grid[0].length.
    • B
      12 3
      Why not B: Confused grid.length with the total element count (3*4=12).
    • C
      3 4Correct
    • D
      3 3
      Why not D: Assumed grid[0].length equals the number of rows instead of the number of columns.
    Explanation

    grid.length gives the number of rows (3). grid[0].length gives the number of columns in row 0 (4). The output is 3 4.

    Key takeaway

    arr.length = number of rows; arr[0].length = number of columns.

  4. Question 4 · Easy

    What is the output of the following code?

    int[][] m = {{2, 4}, {6, 8}};
    for (int r = 0; r < m.length; r++) {
        for (int c = 0; c < m[r].length; c++) {
            System.out.print(m[r][c] + " ");
        }
    }
    
    • A
      2 6 4 8
      Why not A: Traversed column-major (outer loop over columns, inner over rows) instead of row-major.
    • B
      2 4 6 8Correct
    • C
      8 6 4 2
      Why not C: Iterated in reverse order through both dimensions.
    • D
      4 8 2 6
      Why not D: Printed column-major order starting from the second column.
    Explanation

    The outer loop iterates over rows (r=0, then r=1). The inner loop iterates over columns within each row. So the order is m[0][0]=2, m[0][1]=4, m[1][0]=6, m[1][1]=8, printing 2 4 6 8.

    Key takeaway

    Row-major traversal: outer loop over rows, inner loop over columns, visits elements left-to-right, top-to-bottom.

  5. Question 5 · Easy

    What value does the following method return when called with the array {{1, 2}, {3, 4}}?

    public static int total(int[][] arr) {
        int sum = 0;
        for (int r = 0; r < arr.length; r++) {
            for (int c = 0; c < arr[r].length; c++) {
                sum += arr[r][c];
            }
        }
        return sum;
    }
    
    • A
      4
      Why not A: Only summed the last row {3, 4}, not the entire array.
    • B
      6
      Why not B: Summed elements of only one row (e.g., 1+2+3 from a misread traversal).
    • C
      10Correct
    • D
      24
      Why not D: Multiplied elements instead of adding them (123*4=24).
    Explanation

    The nested loop visits every element: arr[0][0]=1, arr[0][1]=2, arr[1][0]=3, arr[1][1]=4. sum = 0+1+2+3+4 = 10.

    Key takeaway

    Nested loops let you accumulate values across all elements of a 2D array.

  6. Question 6 · Easy

    Consider a 2D array representing a grid where each row may have a different length (a jagged array). Which expression safely gives the number of columns in row i?

    • A
      arr.length
      Why not A: This gives the number of rows, not the number of columns in row i.
    • B
      arr[0].length
      Why not B: Always reads row 0's length, which may differ from row i in a jagged array.
    • C
      arr[i].lengthCorrect
    • D
      arr.length[i]
      Why not D: Syntactically invalid; length is a field, not a method, and cannot be subscripted.
    Explanation

    In a jagged array, each row is an independent array and may have a different length. arr[i].length accesses the length of the specific row at index i, making it the safe and correct expression.

    Key takeaway

    Use arr[i].length (not arr[0].length) when rows may have different lengths.

  7. Question 7 · Medium

    What is the output of the following code?

    int[][] t = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    for (int c = 0; c < t[0].length; c++) {
        for (int r = 0; r < t.length; r++) {
            System.out.print(t[r][c] + " ");
        }
    }
    
    • A
      1 2 3 4 5 6 7 8 9
      Why not A: Described row-major order; this code uses column-major order (outer loop over columns).
    • B
      1 4 7 2 5 8 3 6 9Correct
    • C
      3 6 9 2 5 8 1 4 7
      Why not C: Traversed columns in reverse order from last to first.
    • D
      9 8 7 6 5 4 3 2 1
      Why not D: Reversed the entire traversal order.
    Explanation

    The outer loop runs over columns (c=0,1,2) and the inner loop over rows (r=0,1,2). For c=0: t[0][0]=1, t[1][0]=4, t[2][0]=7. For c=1: 2,5,8. For c=2: 3,6,9. Output: 1 4 7 2 5 8 3 6 9.

    Key takeaway

    Swapping loop order to outer-column, inner-row produces column-major (top-to-bottom, left-to-right) traversal.

  8. Question 8 · Medium

    A method receives a 2D array and should return the largest value in the array. Which implementation is correct?

    public static int findMax(int[][] arr) {
        int max = arr[0][0];
        for (int[] row : arr) {
            for (int val : row) {
                if (val > max) max = val;
            }
        }
        return max;
    }
    
    • A
      It always returns arr[0][0] because max is never updated.
      Why not A: Misread the logic; the if-statement inside the loop updates max whenever a larger value is found.
    • B
      It fails to compile because enhanced for-loops cannot iterate over a 2D array's rows.
      Why not B: Enhanced for-loops can iterate over a 2D array, treating each element as an int[] row.
    • C
      It correctly returns the maximum value in the entire 2D array.Correct
    • D
      It returns the wrong result if all values are negative.
      Why not D: Initializing max to arr[0][0] (a real element) handles all-negative arrays correctly; using Integer.MIN_VALUE would also work but is not required.
    Explanation

    The method initializes max to a real array element arr[0][0], then checks every element. If any value exceeds the current max, max is updated. This correctly handles all-negative, all-positive, or mixed arrays.

    Key takeaway

    Initialize max (or min) to arr[0][0], not 0, so the starting value is always a valid array element.

  9. Question 9 · Medium

    What is the output of the following code?

    int[][] g = new int[2][3];
    for (int r = 0; r < g.length; r++) {
        for (int c = 0; c < g[r].length; c++) {
            g[r][c] = r + c;
        }
    }
    System.out.println(g[1][2]);
    
    • A
      0
      Why not A: Assumed all elements remain at their default value of 0 without considering the assignment.
    • B
      2
      Why not B: Evaluated r+c using r=0, c=2 (row 0, col 2) instead of row 1, col 2.
    • C
      3Correct
    • D
      5
      Why not D: Used one-based indices (r=2, c=3) instead of zero-based (r=1, c=2).
    Explanation

    The loop sets each cell to r+c. For the cell at row 1, column 2: g[1][2] = 1 + 2 = 3.

    Key takeaway

    Filling a 2D array with index-based formulas is a common pattern; verify the formula with specific row/col values.

  10. Question 10 · Medium

    The following code attempts to print the sum of the main diagonal of a 3×3 array:

    int[][] m = {{1, 0, 0}, {0, 5, 0}, {0, 0, 9}};
    int diag = 0;
    for (int i = 0; i < m.length; i++) {
        diag += m[i][i];
    }
    System.out.println(diag);
    

    What does it print?

    • A
      0
      Why not A: Assumed only off-diagonal elements are accessed, but m[i][i] hits the diagonal.
    • B
      9
      Why not B: Only accumulated the last diagonal element (m[2][2]=9) instead of all three.
    • C
      14
      Why not C: Summed all non-zero elements (1+5+9=15 is incorrect; 1+4+9 would be 14 if 5 were misread).
    • D
      15Correct
    Explanation

    The loop runs i=0,1,2. m[0][0]=1, m[1][1]=5, m[2][2]=9. diag = 1+5+9 = 15. This is the classic main-diagonal sum pattern.

    Key takeaway

    The main diagonal of an n×n array is accessed with a single loop using arr[i][i].

  11. Question 11 · Hard

    A student writes the following method to count elements equal to a target value in a 2D array:

    public static int count(int[][] arr, int target) {
        int cnt = 0;
        for (int r = 0; r < arr.length; r++) {
            for (int c = 0; c < arr[0].length; c++) {
                if (arr[r][c] == target) cnt++;
            }
        }
        return cnt;
    }
    

    For which input would this method produce incorrect results?

    • A
      A 3×3 array with target 7
      Why not A: A rectangular array where all rows have the same length works correctly with arr[0].length.
    • B
      A 1×1 array with target 0
      Why not B: A single-element rectangular array also works correctly.
    • C
      A jagged array where row 1 has more columns than row 0Correct
    • D
      A 4×4 array with target -1
      Why not D: Negative targets work fine; the issue is not with the target value.
    Explanation

    The inner loop bound arr[0].length assumes all rows have the same length as row 0. If a later row is longer, those extra elements are never visited. If a later row is shorter, an ArrayIndexOutOfBoundsException is thrown. Use arr[r].length to handle jagged arrays safely.

    Key takeaway

    Use arr[r].length in the inner loop bound to safely handle jagged (non-rectangular) 2D arrays.

  12. Question 12 · Hard

    What is the state of array a after the following code executes?

    int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int[] temp = a[0];
    a[0] = a[2];
    a[2] = temp;
    
    • A
      Row 0: {1,2,3}, Row 2: {7,8,9} (unchanged)
      Why not A: Assumed reference swaps don't affect the actual array; in Java, swapping row references changes which row each index points to.
    • B
      Row 0: {7,8,9}, Row 1: {4,5,6}, Row 2: {1,2,3}Correct
    • C
      Row 0: {1,2,3}, Row 1: {8,5,2}, Row 2: {7,4,9}
      Why not C: Confused a row-swap with an element-level transpose operation.
    • D
      Row 0: {7,8,9}, Row 1: {1,2,3}, Row 2: {4,5,6}
      Why not D: Shifted all three rows up by one position instead of swapping rows 0 and 2.
    Explanation

    In Java, a 2D array is an array of references to row arrays. temp = a[0] saves the reference to {1,2,3}. a[0] = a[2] makes row 0 point to {7,8,9}. a[2] = temp makes row 2 point to {1,2,3}. Row 1 is unchanged. Result: row0={7,8,9}, row1={4,5,6}, row2={1,2,3}.

    Key takeaway

    Swapping rows in a 2D array swaps the row references, not individual elements; it is an O(1) operation.