Assignment and Compound Operators in Java
Assignment (=) stores a value in a variable. Java also has a full set of compound assignment operators (+=, -=, etc.) that combine an operation with assignment in one step. Assignments are expressions β they evaluate to the value assigned.
Basic assignment
int x = 10;
x = 20; // reassign
String s = "hello";
Compound assignment
| Operator | Equivalent |
|---|---|
x += y | x = x + y |
x -= y | x = x - y |
x *= y | x = x * y |
x /= y | x = x / y |
x %= y | x = x % y |
x &= y, |=, ^= | bitwise + assign |
x <<= y, >>=, >>>= | shift + assign |
The implicit cast
byte b = 1;
b = b + 1; // β compile error β result is int
b += 1; // β
compound operator inserts an implicit cast
Compound operators silently narrow the result back to the left-hand type. Convenient, but occasionally surprising.
String +=
String s = "hello";
s += " world"; // "hello world"
// Equivalent to s = new StringBuilder(s).append(" world").toString()
Fine for a few concatenations. Inside a loop, use a StringBuilder explicitly β repeated += allocates a new buffer every time.
Assignment returns a value
int y;
int z = (y = 10) + 5; // z = 15, y = 10
String line;
while ((line = reader.readLine()) != null) {
process(line);
}
Chained assignment
int a, b, c;
a = b = c = 0; // all three set to 0
Right-associative: the rightmost c = 0 evaluates to 0, then b = 0, then a = 0.
Common mistakes
=where==was meant βif (flag = true)silently assigns.- Chained assignment with different types β the compound form is simpler and clearer.
- Repeated
+=on strings in a loop β useStringBuilder.
Related
Pillar: Java operators. See also arithmetic, bitwise.