AP CSA Unit 1 Day 16: Repeated Method Calls Mutate Object State

Unit 1, Sections 1.3-1.4 • Cycle 2
Day 16 Advanced Practice • Harder Difficulty Hard
Focus: Compound operators with integer division and modulo

Advanced Practice Question

Consider the following code segment. What is printed?
int x = 23;
int y = 7;
x %= y;
y += x;
x = y / x;
System.out.println(x + " " + y);
Why This Answer?

Trace each line carefully, remembering that all values are int:

Line 1-2: x = 23, y = 7

Line 3: x %= yx = 23 % 7

  23 / 7 = 3 remainder 2x = 2

Line 4: y += xy = 7 + 2 = 9

Line 5: x = y / xx = 9 / 2

  Integer division truncates: 9 / 2 = 4 (not 4.5)

Output: 4 9

Why Not the Others?

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.

Common Mistake
Watch Out!

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.

AP Exam Strategy

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
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.