Assignment Operators: =, +=, -=, *=, /=, %=
What You'll Learn
You'll learn how compound assignment operators let you modify a variable's value and reassign it in one concise step.
The Basic Assignment Operator
You already know the simple assignment operator =, which stores a value in a variable:
int score = 100;
score = score + 10; // score is now 110
Compound Assignment: Shortcuts That Save Typing
Compound assignment operators combine an arithmetic operation with assignment. Instead of writing score = score + 10, you can write score += 10. Both do exactly the same thing, but the compound version is shorter and clearer.
Here are all the compound assignment operators:
int x = 20;
x += 5; // Same as: x = x + 5 (x becomes 25)
x -= 3; // Same as: x = x - 3 (x becomes 22)
x *= 2; // Same as: x = x * 2 (x becomes 44)
x /= 4; // Same as: x = x / 4 (x becomes 11)
x %= 3; // Same as: x = x % 3 (x becomes 2)
Why Use Compound Operators?
- Less typing:
count += 1vscount = count + 1 - Clearer intent: You're modifying the variable, not creating a new value
- Fewer errors: You only write the variable name once, reducing typos
Think of it like updating your bank balance: instead of saying "my balance equals my old balance plus deposit," you simply say "add this deposit to my balance."
Important Detail: Implicit Casting
Compound assignment operators automatically include an implicit cast, which you learned about earlier. This means byte b = 10; b += 5; works without error, even though b = b + 5 would require an explicit cast.
Key Takeaway: Compound assignment operators (+=, -=, *=, /=, %=) combine arithmetic and assignment into one efficient operation, making your code shorter and more readable.