Question 161
What is printed?
int[][] m = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int temp = m[0][1];
for (int i = 0; i < m.length - 1; i++) {
m[i][1] = m[i + 1][1];
}
m[m.length - 1][1] = temp;
System.out.println(m[0][1] + " " + m[1][1] + " " + m[2][1]);Main Solution
Let's trace through the code step by step.
Initial array (column index 1 values):
- m[0][1] = 2
- m[1][1] = 5
- m[2][1] = 8
Step 1: int temp = m[0][1]; → temp = 2
Step 2: The for loop runs for i = 0 and i = 1 (since m.length - 1 = 2, condition is i < 2):
- i = 0:
m[0][1] = m[1][1];→ m[0][1] = 5. Now column 1: {5, 5, 8} - i = 1:
m[1][1] = m[2][1];→ m[1][1] = 8. Now column 1: {5, 8, 8}
Step 3: m[m.length - 1][1] = temp; → m[2][1] = 2. Now column 1: {5, 8, 2}
Step 4: System.out.println(m[0][1] + " " + m[1][1] + " " + m[2][1]); prints: 5 8 2
This is a rotation of the second column (index 1) upward by one position, with the original top value placed at the bottom. The answer is D: 5 8 2.
Teacher Explanation
This question tests understanding of 2D array manipulation and loop tracing. The code performs a cyclic upward rotation of the middle column (index 1) of a 3×3 2D array. Students must carefully track how each assignment in the loop modifies the array before the next iteration reads from it.
Education Coach Advice
When tracing 2D array loops on the AP exam, always track the state of the array after each assignment, not just at the end of the loop. Write out a small table showing the relevant values after each iteration. Also note that saving a value in temp before a loop is a classic rotation pattern — recognize it quickly to save time.
Traps
Common traps:
- Option A (2 5 8): Thinking nothing changes — students may confuse the loop logic or think temp is restored immediately.
- Option B (8 2 5): Reversing the direction of rotation — confusing upward with downward shift.
- Option C (8 5 2): Thinking the entire column is reversed rather than rotated — a common misconception about what the loop does.
The key insight is that the loop shifts values upward one by one (overwriting as it goes), and then temp (the original top value) is placed at the bottom — a classic cyclic rotation pattern.
Answer images

