Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this assignment not require an explicit cast?

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?

like image 207
PrashanD Avatar asked Nov 28 '12 10:11

PrashanD


1 Answers

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.

like image 81
Jon Skeet Avatar answered Sep 24 '22 21:09

Jon Skeet