byte b=9 ;
b=b+6 ;
gives compilation error (possible loss of precision )
why does b=9 not give error whereas b=b+9 give loss
The expression
b = b + 6
is an integer operation as og JLS §4.2.2. As stated in the JLS, each such operation is of type int or long (here: int). So the result is also of type int and it must be cast to byte if you want to assign it to such a variable.
On the other hand, JLS §15.26.2 explains the rules for the compound assignment operator. In short:
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.
This clearly tells us that the compound assignment operator += implicitly does the cast.