AP Computer Science A · Unit 1: Using Objects & Methods
1.4 Compound Assignment Operators
What compound assignment does
Compound assignment operators combine an arithmetic operation with assignment in one step. For example, `x += 5;` means `x = x + 5;`. Other operators include `-=`, `*=`, `/=`, and `%=`. They make code shorter and reduce repetition when updating a variable's own value.
Order of operations matters
Java evaluates the right side fully before applying the operator to the variable. `x *= y + 2;` is equivalent to `x = x * (y + 2);`, NOT `x = x * y + 2;`. The whole right-hand expression acts as a single operand before combining with the original variable.
Type casting with compound operators
Compound assignment can implicitly cast the result back to the variable's original type. If `int x = 5;` then `x /= 2;` performs integer division, giving `x = 2` (not 2.5), since `x` stays an `int`. This differs from writing it as two separate statements if types mismatch.
Key terms
- Compound assignment operator
- An operator that combines an arithmetic operation with assignment, e.g., `+=`, `-=`, `*=`, `/=`, `%=`.
- x += 5;
- Equivalent to `x = x + 5;` — adds 5 to x and stores the result back in x.
- x *= y + 2;
- Equivalent to `x = x * (y + 2);` — the right side is evaluated as one expression first.
- Integer division with /=
- If the variable is an int, `/=` performs integer division and truncates any decimal part.
- %= operator
- Performs modulo (remainder) division and assigns the result back to the variable, e.g., `x %= 4;`.
Try an AP-style question
Code
int x = 5; x *= 2; x -= 3;
What is x?
- 7
- 13
- 4
- 10
Show the answer
A. 5 × 2 = 10; 10 − 3 = 7.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 1.4 free in APrep