开发者

why byte += 1 compile but byte = byte + 1 not?

开发者 https://www.devze.com 2023-02-10 03:20 出处:网络
If I have a byte variable: byte b = 0; why does the following work: b++; b += 1; // compiles ... but this does not ?

If I have a byte variable: byte b = 0;

why does the following work:

   b++;
   b += 1; // compiles

... but this does not ?

   b = b + 1; // compile error

Does compiler understand first as byte and second as int ?

[EDIT]

I know casting but I开发者_运维问答 want to draw your attention to the b++, b += 1 and b = b + 1

I think they are equal so why compiler differs them ? what is the difference between

  b += 1 and b = b + 1 ?


Because b += 1 is an equivalent to b = (byte)(b + 1), whereas type of b + 1 is promoted to int (JLS §5.6.2 Binary Numeric Promotion) and therefore its result cannot be assigned to byte without explicit conversion.

From JLS, §15.26.2 Compound Assignment Operators:

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.


Possible loss of precision is the problem. Cast it and it is OK.

b = (byte) (b + 1);


Yes, the result of the +-operation is int, so a cast is needed in order to assign it to a byte variable.


In java the default for integers is int, and for floating point numbers it is double. So b is by default converted to integer to perform the operation. So the resultant answer needs to be typecasted before being stored to prevent any possible loss of precision. But b+=1 does it automatically.


operands of type byte and short are automatically promoted to int before being handed to the operators

so when you do byte b= b + 1; it considers it "int" as an operation is performed on byte value. so to avoid this we use b+=1; here it is automatically typecasted to byte.


You need to cast to byte:

b = (byte) (b + 1);


Doing b + 1 widens the result to integer, and assigning back to byte b would cause loss of precision. Explained: Conversions and Promotions. But I like axtavt's answer better.


I don't buy the argument about loss of precision, since the compiler won't protect you in a similar fashion when dealing with ints and longs. I think the real answer lies with the JLS simply having better support for ints than bytes, as stated in this answer: https://stackoverflow.com/a/13211737/567000

0

精彩评论

暂无评论...
验证码 换一张
取 消