➗ Operators & Expressions · Beginner

Assignment & compound assignment in Java

+=, -=, … include an implicit cast (byte b += 1 compiles).

🧩 The mysteryb = 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 % 4
🔮 Predict it

Your turn

What does this print?

int x = 4;
x *= 1 + 2;
System.out.println(x);
  1. 12
  2. 6
  3. Compile 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

✗ Doesn't compile
byte b = 10;
b = b + 5;

b + 5 is promoted to int, and int → byte needs an explicit cast.

✓ Compiles
byte b = 10;
b += 5;   // 15

Compound assignment includes the hidden (byte) cast.

🔮 Predict it

Your turn

What does this print?

byte b = 125;
b += 10;
System.out.println(b);
  1. 135
  2. 127
  3. -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 the real world

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

  1. x += 5 means x = (type of x) (x + 5)
  2. The whole right side is evaluated first: x *= 2 + 3 → x * 5
  3. The hidden cast can silently overflow
  4. Assignment is right-associative: a = b = 4
🤯 Did you know?

+= 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);
  1. Compile error
  2. Throws ArithmeticException
  3. 15
  4. 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);
  1. Compile error
  2. 15
  3. Throws ArithmeticException
  4. 105
Check your answer

Compile error. b + 5 is promoted to int, and assigning an int expression to a byte requires an explicit cast.

Next: == on two Strings that both say "cat" can be false. Equality in Java has two meanings.