How does Java's compound assignment operator (like +=) implicitly include a narrowing cast that a corresponding explicit expanded assignment (x = x + y) does not, and what surprising behavior results from this?
Short answer
A compound assignment operator like x += y is specified to be exactly equivalent to x = (T)(x + y), where T is x's own declared type -- meaning it includes an IMPLICIT narrowing cast back to x's type, even if the intermediate expression x + y would normally require an explicit…
Advertisement
AModel answer
A compound assignment operator like x += y is specified to be exactly equivalent to x = (T)(x + y), where T is x's own declared type -- meaning it includes an IMPLICIT narrowing cast back to x's type, even if the intermediate expression x + y would normally require an explicit cast to avoid a compile error as a standalone expanded assignment -- this means code like `byte b = 10; b += 5;` compiles and works fine (silently narrowing the int result of the addition back to byte), while the seemingly equivalent expanded form `b = b + 5;` would actually FAIL to compile without an explicit cast, since b + 5 promotes to int and assigning an int to a byte variable requires an explicit narrowing cast.
byte b = 10;
b += 5; // compiles fine -- compound assignment includes an IMPLICIT cast back to byte
System.out.println(b); // 15
// byte b2 = 10;
// b2 = b2 + 5; // COMPILE ERROR! b2 + 5 is promoted to int, assigning int to byte needs an explicit cast
byte b2 = 10;
b2 = (byte)(b2 + 5); // this expanded form DOES need the explicit cast to compileReal-world example
A developer surprised that byte counter += 1; compiles without any cast, while the seemingly equivalent counter = counter + 1; produces a compile error, learns this is because compound assignment operators specifically include an implicit narrowing cast the expanded form doesn't automatically provide.
Likely follow-ups
- What specific risk does this implicit compound-assignment cast introduce, given it can silently narrow and potentially lose data without any visible cast in the source code?
- Does this same implicit-cast behavior apply to ALL compound assignment operators (+=, -=, *=, /=), or just some of them?
Related topics