Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- A compound assignment operator performs the arithmetic operation between the value on the left and the value on the right, then assigns the result to the variable on the left.
- The operators are
+=,-=,*=,/=and%=; they can be used in place of=in numeric expressions. - The post-increment
++and post-decrement--add 1 to, or subtract 1 from, a numeric variable and store the new value. - Prefix forms (
++x) and uses inside other expressions (arr[x++]) are outside the course and exam.
Key relationships
| Statement | Equivalent | Result for int x = 8 |
|---|---|---|
x += 3; |
x = x + 3; |
11 |
x -= 3; |
x = x - 3; |
5 |
x *= 3; |
x = x * 3; |
24 |
x /= 3; |
x = x / 3; |
2 (integer division) |
x %= 3; |
x = x % 3; |
2 |
x++; |
x += 1; |
9 |
x--; |
x -= 1; |
7 |
x *= 2 + 3; |
x = x * (2 + 3); |
40 |
x /= 2 * 2; |
x = x / (2 * 2); |
2 |
For double d = 9; d /= 2; the result is 4.5.
The three jobs compound assignment does
- Accumulate:
sum += price;keeps a running total. - Count:
count++;goes up by one each time;remaining--;counts down. - Scale or wrap:
price *= 2;doubles;pot /= 4;shares out whole units;position %= 10;keeps a non-negative value in the range 0 to 9.
Statement order matters: from 10, x += 5; x *= 2; leaves 30, but x *= 2; x += 5; leaves 25.
Assumptions and conventions
- The right side is evaluated in full before it is combined with the variable.
- Use
++and--as separate statements, after the variable. - If an
intvariable is updated with adoublevalue (n *= 1.5;), Java converts the result back toint, truncating the fraction. - No calculator is allowed on the exam, so trace by hand with a table, one row per statement.
Mistakes to avoid
- Reading
x *= 2 + 3asx = x * 2 + 3. - Writing
=+instead of+=.x =+ 5just stores 5. - Forgetting integer division when
/=is applied to anint. - Using the original value of a variable instead of the value left by the previous statement.
- Using
++inside an expression or in prefix form, which the course does not use. - Treating
%=as a percentage. It stores the remainder.
Quick self-check
- After
int a = 12; a /= 5;what isa? (2) - After
int b = 6; b *= 1 + 2;what isb? (18) - After
double d = 7; d /= 2;what isd? (3.5) - After
int c = 9; c %= 4; c++;what isc? (1 then 2, so 2) - What does
int n = 3; n += 2.9;leave inn? (5, because 5.9 is truncated when stored)
Next: practice questions.