loss in precision in JAVA while using byte datatype

前端 未结 4 984
眼角桃花
眼角桃花 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:51

    During expression evaluation there is an implicit type casting to int, due to the promotion rules in java

    So intead of :

    byte b=1;
    b=b+1;  //will give error
    

    Write:

    b=(byte)b+1;
    

    Here are some links you can refer:

    Link 1

    Link 2

    Link 3

提交回复
热议问题