AP CSA Unit 1 Day 16: Repeated Method Calls Mutate Object State
Share
Advanced Practice Question
int x = 23;
int y = 7;
x %= y;
y += x;
x = y / x;
System.out.println(x + " " + y);
Trace each line carefully, remembering that all values are int:
Line 1-2: x = 23, y = 7
Line 3: x %= y → x = 23 % 7
23 / 7 = 3 remainder 2 → x = 2
Line 4: y += x → y = 7 + 2 = 9
Line 5: x = y / x → x = 9 / 2
Integer division truncates: 9 / 2 = 4 (not 4.5)
Output: 4 9
B) 4.5 9 — 9 / 2 does not produce 4.5 when both operands are int. Integer division in Java always truncates the decimal portion. The result is 4, not 4.5.
C) 3 9 — This confuses the modulo (%) and division (/) operations. 23 % 7 gives the remainder (2), not the quotient (3). After that, 9 / 2 = 4.
D) 2 9 — This correctly computes x = 2 after the modulo but forgets to update x in line 5. The final assignment x = y / x changes x from 2 to 4.
Two integer arithmetic traps in one problem: (1) The modulo operator % gives the remainder, not the quotient. 23 % 7 = 2 because 7 goes into 23 three times (21) with 2 left over. (2) Integer division truncates toward zero. 9 / 2 = 4, not 4.5. Java does not round — it drops the decimal entirely.
For compound assignment questions, rewrite each line as a full assignment first: x %= y becomes x = x % y. Then trace step by step. On the AP exam, always ask: "Are both operands int?" If yes, the result is int and any decimal is truncated. This catches many students off guard with expressions like 9 / 2.
Keep Building Mastery!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs