loss in precision in JAVA while using byte datatype

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

    When adding bytes, the result is an integer, so that you don't get byte overflow.

    You should try casting it:

    b=(byte)(b+9);
    

提交回复
热议问题