Unit 1 Cycle 1 Day 7: Increment, Decrement, and Modulo Assignment
Share
Increment, Decrement, and Modulo Assignment
Section 1.4 — Compound Assignment Operators
Key Concept
String concatenation in Java uses the + operator, but its behavior changes depending on the operand types. When one operand is a String, Java converts the other operand to a String and concatenates them. Evaluation proceeds left to right, so 2 + 3 + "hello" produces "5hello", not "23hello". The += compound assignment operator works with strings too: s += "world" appends to the existing string. Remember that strings are immutable — concatenation always creates a new String object.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 4 9
Trace each line carefully:
Start: p = 23, q = 7
p %= q: p = 23 % 7 = 2 (7 goes into 23 three times = 21, remainder 2)
q += p: q = 7 + 2 = 9
p = q / p: p = 9 / 2 = 4 (integer division truncates 4.5 to 4)
Output: 4 9
Why Not the Others?
(B) This confuses the final division. 9 / 2 = 4, not 3. You might get 3 if you confused p with the quotient from the first line (23 / 7 = 3), but that is not what % computes.
(C) This correctly computes p = 2 after modulo but forgets to update p in the final line. The line p = q / p reassigns p from 2 to 4.
(D) The value of q changes in line 3. q += p updates q from 7 to 9.
Common Mistake
Two traps: (1) % gives the remainder, not the quotient. 23 % 7 = 2 because 7 * 3 = 21 with 2 left over. (2) Integer division 9 / 2 = 4, not 4.5. Java truncates the decimal.
AP Exam Tip
When variables are used on both sides of an assignment, always use the current value. After p %= q, the value of p is now 2, and that new value is what gets used in subsequent lines.