byte b1 = 3;
byte b2 = 0;
b2 = (byte) (b2 + b1); // line 3
System.out.println(b2);
b2 = 0;
b2 += b1; // line 6
System.out.println(b2);
On line 3, it’s a compiler error if we don’t typecast the result to a byte — that may be because the result of addition is always int and int does not fit into a byte. But apparently we don’t have to typecast on line 6. Aren’t both statements, line 3 and line 6, equivalent? If not then what else is different?
Yes, the two lines are equivalent – but they use different parts of the language, and they’re covered by different parts of the JLS. Line 3 is the normal + operator, applied to bytes which have been promoted to
int, giving anintresult. That has to be cast before you can assign it back to abytevariable.Line 6 is a compound assignment operator as described in section 15.26.2 of the JLS:
It’s the last part (as highlighted) that makes it different.
In fact, the start of the section shows the equivalence: