loss in precision in JAVA while using byte datatype

前端 未结 4 985
眼角桃花
眼角桃花 2021-01-23 21:04
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

4条回答
  •  日久生厌
    2021-01-23 21:59

    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.

提交回复
热议问题