EMZETT.
Login

Assignment Operators

In short: Operators that assign a value to a variable — from simple = to combined shorthand forms like +=.

In more detail: Combined assignment operators (+= -= *= /= %=) are shorthand: x += 5; means the same as x = x + 5;. This reduces typing effort and sources of error for repeated self-updates of a variable, e.g. in loops.

In Depth

Alongside the arithmetic shorthand forms, there are also bitwise combined assignments (&= |= ^= <<= >>= >>>=) for bit operations. Important: for +=/-=/etc., Java automatically performs an implicit cast when needed, which a spelled-out assignment would not allow:

byte b = 10;
b += 5;        // works - implicit cast back to byte
// b = b + 5;  // would NOT compile! b + 5 is of type int,
                // and an int can't be assigned to a byte without an explicit cast
int x = 10;
x *= 2 + 3;    // caution: equals x = x * (2 + 3), i.e. x = 50, NOT x = x*2 + 3

This “hidden” cast rule for += and friends is a popular exam mistake: byte b = 10; b += 5; compiles, but byte b = 10; b = b + 5; does not, even though both lines are meant to do the same thing content-wise. The reason: += is technically not a pure shorthand, but implicitly inserts a cast back to the variable’s original type.

Increment/decrement as a special case

++ and -- are closely related but standalone operators (not +=/-= with 1) — they exist as prefix (++x) and postfix (x++) with a different return value within the same expression:

int x = 5;
int a = x++; // a = 5 (old value is returned), AFTERWARDS x becomes 6
int y = 5;
int b = ++y; // y FIRST becomes 6, b = 6 (new value is returned)

Outside of a compound expression (i.e. as a standalone statement x++;), the difference is irrelevant — both increase x by 1 equally. Within more complex expressions (array[i++] = array[i]), however, the order can lead to subtle, hard-to-follow bugs, which is why many style guides recommend not nesting ++/-- inside larger expressions.

Chained assignments

The simple assignment operator = itself returns a value (the assigned value), which allows several assignments to be chained:

int a, b, c;
a = b = c = 10; // all three variables receive the value 10

This works from right to left: first c = 10 is evaluated (result: 10), then b = 10, then a = 10. In practice this is used rather sparingly, since it can reduce readability.

Comparison to other languages

The principle of combined assignment operators (+=, -=, etc.) is not Java-specific, but is found almost identically in C, C++, JavaScript, and Python (there, however, without Java’s implicit narrowing cast, since Python has no fixed integer sizes).

See also: Operators, Declaring Variables, Type Casting