The Assignment Operator (=) in Java - Quiz
Total: 2 questions
1. How does the assignment operator = work in Java, and what is its associativity?
How does the assignment operator = work in Java, and what is its associativity?
Syntax: variable = expression; — the right-hand expression is evaluated first, then its value is stored into the variable on the left. The left side must be a modifiable variable (an l-value); the right side is any expression of a compatible type.
The = operator is right-associative: the chain a = b = c = 5 groups as a = (b = (c = 5)) and runs right to left. An assignment is itself an expression whose value is the value that was assigned, which is exactly why such chains work.
2. Why does b += 5; compile while b = b + 5; does not, when b is a byte?
byte b = 10;
b += 5; // compiles
b = b + 5; // compile error
Why does b += 5; compile while b = b + 5; does not, when b is a byte?
byte b = 10;
b += 5; // compiles
b = b + 5; // compile errorIt comes down to a quirk of compound assignment operators (JLS 15.26.2). The form E1 op= E2 is NOT literally equivalent to E1 = E1 op E2 — it is actually equivalent to E1 = (T)((E1) op (E2)), where T is the type of the left-hand side. In other words, += has an implicit narrowing cast to the variable type built in.
So b += 5; means b = (byte)(b + 5); and compiles cleanly. A plain assignment b = b + 5; has no such cast: when b + 5 is evaluated, both operands are promoted to int, and an int result cannot be assigned to a byte without an explicit cast. To make it compile you must write b = (byte)(b + 5);.
That same hidden cast in +=, -=, *= and friends can silently truncate a value on overflow — an easy detail to forget.