Consider this code:
byte b=1;
long l=1000;
b += l;
I would expect the last statement to require an explicit cast because,
b+=l
is evaluated as b = b+l
and
(b+l)
part gives an integer.
Integer cannot be assigned to byte without an explicit cast?
Well to start with, b+l
gives a long
, not an int
...
... but compound assignment operators have other behaviour. As per JLS section 15.26.2:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
Note the cast to T
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With