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.
- 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]?- A3Why not A: Confused row 0 index 2 (value 3) with row 1 index 2.
- B5Why not B: Read arr[1][1] (the center element) instead of arr[1][2].
- C6Correct
- D8Why not D: Read arr[2][1] by swapping row and column indices.
ExplanationIn Java,
arr[row][col]uses zero-based indexing. Row 1 is{4, 5, 6}and column index 2 of that row is6. Soarr[1][2] == 6.Key takeawayarr[r][c] means row r, column c, both zero-indexed.
- A
- 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.
ExplanationIn 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 takeawaynew int[rows][cols]: first dimension is rows, second is columns.
- A
- 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 3Why not A: Swapped the meanings of grid.length and grid[0].length. - B
12 3Why not B: Confused grid.length with the total element count (3*4=12). - C
3 4Correct - D
3 3Why not D: Assumed grid[0].length equals the number of rows instead of the number of columns.
Explanationgrid.lengthgives the number of rows (3).grid[0].lengthgives the number of columns in row 0 (4). The output is3 4.Key takeawayarr.length = number of rows; arr[0].length = number of columns.
- A
- 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 8Why 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 2Why not C: Iterated in reverse order through both dimensions. - D
4 8 2 6Why not D: Printed column-major order starting from the second column.
ExplanationThe 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 takeawayRow-major traversal: outer loop over rows, inner loop over columns, visits elements left-to-right, top-to-bottom.
- A
- 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; }- A4Why not A: Only summed the last row {3, 4}, not the entire array.
- B6Why not B: Summed elements of only one row (e.g., 1+2+3 from a misread traversal).
- C10Correct
- D24Why not D: Multiplied elements instead of adding them (123*4=24).
ExplanationThe 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 takeawayNested loops let you accumulate values across all elements of a 2D array.
- A
- 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.lengthWhy not A: This gives the number of rows, not the number of columns in row i. - B
arr[0].lengthWhy 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.
ExplanationIn a jagged array, each row is an independent array and may have a different length.
arr[i].lengthaccesses the length of the specific row at index i, making it the safe and correct expression.Key takeawayUse arr[i].length (not arr[0].length) when rows may have different lengths.
- A
- 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 9Why 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 7Why not C: Traversed columns in reverse order from last to first. - D
9 8 7 6 5 4 3 2 1Why not D: Reversed the entire traversal order.
ExplanationThe 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 takeawaySwapping loop order to outer-column, inner-row produces column-major (top-to-bottom, left-to-right) traversal.
- A
- 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; }- AIt always returns
arr[0][0]becausemaxis never updated.Why not A: Misread the logic; the if-statement inside the loop updates max whenever a larger value is found. - BIt 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.
- CIt correctly returns the maximum value in the entire 2D array.Correct
- DIt 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.
ExplanationThe method initializes
maxto a real array elementarr[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 takeawayInitialize max (or min) to arr[0][0], not 0, so the starting value is always a valid array element.
- A
- 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]);- A0Why not A: Assumed all elements remain at their default value of 0 without considering the assignment.
- B2Why not B: Evaluated r+c using r=0, c=2 (row 0, col 2) instead of row 1, col 2.
- C3Correct
- D5Why not D: Used one-based indices (r=2, c=3) instead of zero-based (r=1, c=2).
ExplanationThe loop sets each cell to r+c. For the cell at row 1, column 2: g[1][2] = 1 + 2 = 3.
Key takeawayFilling a 2D array with index-based formulas is a common pattern; verify the formula with specific row/col values.
- A
- 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?
- A0Why not A: Assumed only off-diagonal elements are accessed, but m[i][i] hits the diagonal.
- B9Why not B: Only accumulated the last diagonal element (m[2][2]=9) instead of all three.
- C14Why not C: Summed all non-zero elements (1+5+9=15 is incorrect; 1+4+9 would be 14 if 5 were misread).
- D15Correct
ExplanationThe 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 takeawayThe main diagonal of an n×n array is accessed with a single loop using arr[i][i].
- A
- 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?
- AA 3×3 array with target 7Why not A: A rectangular array where all rows have the same length works correctly with arr[0].length.
- BA 1×1 array with target 0Why not B: A single-element rectangular array also works correctly.
- CA jagged array where row 1 has more columns than row 0Correct
- DA 4×4 array with target -1Why not D: Negative targets work fine; the issue is not with the target value.
ExplanationThe inner loop bound
arr[0].lengthassumes 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. Usearr[r].lengthto handle jagged arrays safely.Key takeawayUse arr[r].length in the inner loop bound to safely handle jagged (non-rectangular) 2D arrays.
- A
- Question 12 · Hard
What is the state of array
aafter 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;- ARow 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.
- BRow 0: {7,8,9}, Row 1: {4,5,6}, Row 2: {1,2,3}Correct
- CRow 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.
- DRow 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.
ExplanationIn 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] = tempmakes 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 takeawaySwapping rows in a 2D array swaps the row references, not individual elements; it is an O(1) operation.
- A