UNIT 1: USING OBJECTS AND METHODS · TOPIC 1.6
1.6 Compound Assignment Operators
Shorthand that shows up in every loop. The traps are the hidden cast in compound operators and what ++ does inside an expression.
What you need to know
x += 5meansx = x + 5. Same for-=,*=,/=,%=.- Compound operators include an implicit cast back to the variable's type: if
xis an int,x /= 2.0compiles and stores an int.x = x / 2.0would not compile. x++and++xboth add 1 to x.x--and--xsubtract 1. On the exam these are used as standalone statements, where the pre/post distinction doesn't matter.- The AP exam does not test
x++inside larger expressions (likey = x++). Keep increments on their own line. x *= 2 + 3meansx = x * (2 + 3)— the whole right side is computed first.- These operators work on doubles too:
total += 0.5;
Worked example
int x = 10; x += 3; // 13 x -= 5; // 8 x *= 2; // 16 x /= 3; // 5 (integer division) x %= 4; // 1 x++; // 2 x *= 1 + 1; // 4 (x * 2, not x * 1 + 1)
Exam tip: Rewrite every compound operator as its long form before tracing:
x *= a + b → x = x * (a + b). The parentheses are the part students drop.Going deeper
The nuance, edge cases, and connections that turn a 3 into a 5.
x op= exprmeansx = x op (expr)— the entire right side is parenthesized.x *= 2 + 3isx = x * 5, notx * 2 + 3.- The hidden cast: compound operators cast the result back to the variable's type.
int x = 10; x /= 4.0;compiles and leaves x = 2 (10 / 4.0 = 2.5, cast to int). The long formx = x / 4.0would be a compile error (double to int). This asymmetry is occasionally tested. x++and++xare identical as standalone statements. The exam only uses them that way — inside larger expressions (y = x++) is explicitly out of scope, so you won't see it.x--and--xlikewise.x += 1,x++,x = x + 1are all the same statement.- Compound operators work on doubles (
total += 0.25) and, for+=only, on Strings (s += "x"concatenates). - Loop updates almost always use these:
i++,i += 2,i--. Reading them fluently speeds up every loop question.
Mistakes that cost points
- Forgetting the implied parentheses.
x -= 2 * 3subtracts 6, not 2 then times 3. - Misreading
x -= 5asx = -5. It subtracts 5 from x. - Thinking
x++inside a loop body increments twice with the loop header. Each increment is one. If both the header and body increment, i goes up by 2 per iteration.
Practice questions
Written in the style of the real exam. Try each one before revealing the answer.
Q1 What is the value of
n after the following code?
int n = 7; n += 3; n /= 2; n *= n;
Show answer
Answer: A. 7 + 3 = 10. 10 / 2 = 5. 5 * 5 = 25.
Q2 What is the value of
total after int total = 12; total -= 2 * 3;?Show answer
Answer: B. The right side (2 * 3 = 6) is computed first, then total = 12 - 6 = 6.
Key vocabulary
- Compound assignment
- operators like += that combine arithmetic with assignment
- Increment (++)
- adds 1 to a variable
- Decrement (--)
- subtracts 1 from a variable