Web Analytics

Assignment Operators

Beginner ~10 min read

Assignment operators are used to assign values to variables. While the basic equals sign = is the most common, Java offers "compound" assignment operators that perform a math operation and assignment in one step.

Assignment Operators List

Operator Example Equivalent To
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
Output
Click Run to execute your code

Hidden Type Casting

Compound assignment operators like += have a special feature: they automatically perform a type cast.

Consider adding an int to a byte (remember, byte + int results in int):

byte b = 10;
// b = b + 1;  // Compile ERROR! (int cannot be converted to byte) 

// Correct way with explicit cast:
b = (byte)(b + 1);

// SHORTCUT with +=
b += 1;  // Works! Cast is implicit.

The compiler treats E1 op= E2 as E1 = (Type of E1)(E1 op E2).

Watch Out: Because of hidden casting, you might trigger an overflow without realizing it!
byte b = 127; b += 1; // b becomes -128 (overflow)

Summary

  • Use = to assign a value.
  • Use +=, -=, etc. for cleaner code when modifying a variable by a value.
  • Compound assignment operators automatically handle type casting, which is convenient but hides potential data loss or overflows.