1.6 - Compound Assignment Operators
Compound assignment operators let you combine an arithmetic operation with an assignment in one step:
+=, -=, *=, /=, and %=. They take the value on the left, apply the operation with the value on the right, and store the result back into the variable on the left.int score = 10; score += 5; // same as score = score + 5, now 15 score *= 2; // now 30
int n = 17; n -= 2; // n = 15 n /= 4; // n = 3, int division n %= 2; // n = 1
The whole right side gets evaluated first, and then the operation is applied with that result:
int x = 4; x *= 2 + 3; // x = x * (2 + 3) = 4 * 5 = 20, not 4 * 2 + 3 = 11
The post-increment (
++) and post-decrement (--) operators add or subtract 1 from a variable’s value.int count = 0; count++; // count is now 1 count--; // count is now 0 again
So
x++, x += 1, and x = x + 1 all do the same thing.Note: prefix form (
++x) and using increment/decrement inside other expressions (like arr[x++]) are both outside the scope of this course.Here’s the kind of trace you’ll see on the exam. Track each variable line by line:
int x = 7; int y = 3; x += y; // x = 10 y *= 2; // y = 6 x %= y; // x = 10 % 6 = 4 y--; // y = 5 x /= 2; // x = 2 System.out.println(x + " " + y);
Output:
2 5