Unit 1.6: Compound Assignment Operators
Compound Assignment
- Compound assignment operators (
+=,-=,*=,/=,%=) provide a shorthand for performing an operation and an assignment in a single step.
- Compound operators are a convenience.
x += 5is exactly the same asx = x + 5. The right-hand side is always fully evaluated before the operation and assignment occur.
- Operators:
+=,-=,*=,/=,%= - Evaluation: The expression on the right side is evaluated first, then the operation is performed with the variable on the left, and finally, the result is assigned back to the variable.
| Operator | Example | Equivalent to |
|---|---|---|
+= |
c += a; |
c = c + a; |
-= |
c -= a; |
c = c - a; |
*= |
c *= a; |
c = c * a; |
/= |
c /= a; |
c = c / a; |
%= |
c %= a; |
c = c % a; |
Task: Using compound assignment
int score = 10;
score += 5; // score is now 15
score *= 2; // score is now 30
score %= 7; // score is now 2 (30 % 7 = 2)
Increment and Decrement
- Increment (
++): Adds 1 to the variable.x++is equivalent tox = x + 1orx += 1.
- Decrement (
--): Subtracts 1 from the variable.x--is equivalent tox = x - 1orx -= 1.
++and--are specific shorthand for adding or subtracting exactly 1. They are widely used in loops and counting logic.
Task: Using unary increment and decrement operators.
int count = 0;
count++; // count is now 1
count--; // count is now 0
EXCLUSION STATEMENT: The use of increment and decrement operators in prefix form (e.g.,
++x) or inside other expressions (e.g.,arr[x++]) is outside the scope of the exam. You only need to know the postfix form (e.g.,x++) as a standalone statement.
Prefix vs Postfix (Out of Scope Examples)
The side of the variable on which the increment or decrement operator is placed matters. For example:
int x = 10;
int y = ++x;
System.out.println(x); // This will print 11
int z = x++;
System.out.println(z); // This will print 11 as well
In the above example, y is assigned the value of x after it is incremented, because the unary operator is before the variable x.
Variable z first gets the existing value of x, and then x is incremented, because the unary operator is after the variable name.
Additional Prefix Examples
Here are more examples of how prefix and postfix operators behave differently when used in expressions:
int a = 5;
int b = --a; // Prefix decrement
// a becomes 4 immediately. b is assigned 4.
// Result: a=4, b=4
int c = 10;
int d = c--; // Postfix decrement
// d is assigned the current value of c (10). Then c becomes 9.
// Result: c=9, d=10
int i = 3;
int result = 5 * ++i; // Prefix increment has precedence
// i becomes 4. Then 5 * 4 is calculated.
// result is 20.