Assignment & compound assignment in Java
+=, -=, … include an implicit cast (byte b += 1 compiles).
b = b + 1; won't compile when b is a byte. b += 1; compiles fine. Aren't they the same thing? Not quite...= is an expression
= stores the right side in the variable, and the whole assignment also has a value: the value stored. Assignment groups right to left, which is why chains work: b = 4 runs first, then its value goes into a.
int a, b;
a = b = 4; // a = (b = 4)Compound shortcuts
Compound operators combine an operation with assignment. For an int, total += 5 has exactly the same effect as total = total + 5.
x += 5; // x = x + 5
x -= 2; // x = x - 2
x *= 3; // x = x * 3
x /= 2; // x = x / 2
x %= 4; // x = x % 4Your turn
What does this print?
int x = 4;
x *= 1 + 2;
System.out.println(x);126Compile error
Show the answer
The entire right side is evaluated first: x = x * (1 + 2) = 4 * 3 = 12, not x * 1 + 2.
The hidden cast
Precisely, x += y means x = (type of x) (x + y). For a byte that matters: b + 5 is an int (numeric promotion!), and += quietly casts it back to byte.
byte arithmetic
byte b = 10;
b = b + 5;b + 5 is promoted to int, and int → byte needs an explicit cast.
byte b = 10;
b += 5; // 15Compound assignment includes the hidden (byte) cast.
Your turn
What does this print?
byte b = 125;
b += 10;
System.out.println(b);135127-121
Show the answer
125 + 10 = 135 as an int, then the hidden (byte) cast keeps the low 8 bits, which wraps to -121. No error, no warning: the cast that lets it compile also hides the overflow.
In real projects
total += price and retries -= 1 are everywhere, and for int, long and double they're perfectly safe. The hidden cast only bites with byte, short and char, typically in low-level buffer and image code.
Key takeaways
- x += 5 means x = (type of x) (x + 5)
- The whole right side is evaluated first: x *= 2 + 3 → x * 5
- The hidden cast can silently overflow
- Assignment is right-associative: a = b = 4
+= works on Strings too: s += "!" appends. Behind the scenes it builds a brand-new String every time.
Practice questions
What does this print?
byte b = 10;
b += 5;
System.out.println(b);- Compile error
- Throws ArithmeticException
- 15
- 105
Check your answer
15. b += 5 compiles because compound assignment means b = (byte) (b + 5).
What does this print?
byte b = 10;
b = b + 5;
System.out.println(b);- Compile error
- 15
- Throws ArithmeticException
- 105
Check your answer
Compile error. b + 5 is promoted to int, and assigning an int expression to a byte requires an explicit cast.