1.6 Compound assignment operatorsShortcuts that update a variable

A compound assignment operator does an operation and an assignment in one step. x += 5; means x = x + 5;. The same pattern works for every arithmetic operator: -=, *=, /= and %=. The usual type rules still apply, so if x is an int, x /= 2; is integer division.
Adding or subtracting exactly 1 is so common it has its own operators: x++; adds 1 to x, and x--; subtracts 1. On the AP exam these are used only as stand-alone statements, never buried inside a bigger expression. (Java also has ++x, but it's outside the AP subset.)
?Wait, why does x = x + 5 make sense?
| Statement | Same as | pts after |
|---|---|---|
| int pts = 10; | 10 | |
| pts += 5; | pts = pts + 5; | 15 |
| pts *= 3; | pts = pts * 3; | 45 |
| pts -= 4; | pts = pts - 4; | 41 |
| pts /= 2; | pts = pts / 2; | 20 |
| pts %= 7; | pts = pts % 7; | 6 |
| pts++; | pts = pts + 1; | 7 |
?Wait, what does % do again?
I thought about it. Show me
What is printed?
int coins = 23; coins %= 10; coins *= 4; coins++; coins -= 20; coins /= 2; System.out.println(coins);
- coins %= 10 means coins = 23 % 10, which is 3.
- coins *= 4 makes it 12. coins++ makes it 13.
- coins -= 20 makes it 13 - 20, which is -7.
- coins /= 2 is -7 / 2 with ints. The exact answer is -3.5, and truncating toward zero gives -3.
Why?
Truncation moves toward zero, so negative results round up toward zero, not down. -7 / 2 is -3, not -4.
Answer: -3
Stuck? Get a hint
- Rewrite each line in its long form: coins = coins % 10; and so on.
- Keep a column with the value of coins after each line.
- The last step is -7 / 2 with two ints. Which way does truncation go?
double d = 5; int k = 5; d /= 2; k /= 2; System.out.println(d + " " + k);
- A2.5 2
- B2.5 2.5
- C2 2
- D2.0 2
Show the answer
A. d is a double, so d /= 2 is 5.0 / 2, which is 2.5. k is an int, so k /= 2 is 5 / 2, which is 2. Choice B is the trap: the shortcut doesn't change the rules, so int division still truncates.
Long chains of updates are trace-table questions. Make one column per variable and one row per line, and write the value after every line. Students who do this in their heads are the ones who pick the trap answer.