Why b=b+1 when b is a byte won't compile but b+=1 compiles

This question already has an answer here:

  • Why don't Java's +=, -=, *=, /= compound assignment operators require casting? 11 answers

  • This is an interesting question. See 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.

    So when you are writing b+=1; , you are actually casting the result into a byte , which is the similar expressing as (byte)(b+1) and compiler will know what you are talking about. In contrast, when you use b=b+1 you are adding two different types and therefore you'll get an Incompatible Types Exception .


    the Error you get is because of the operations with different data types and that can cause an overflow.

    when you do this:

    byte b = 127;
    b=b+1; 
    

    you generate an overflow, so the solution would be casting the result

    b=(byte) (b+1); 
    

    Because can't convert int to byte

    You can try:

    b=(byte) (b+1);

    链接地址: http://www.djcxy.com/p/12794.html

    上一篇: + = b是否真的等于a = a + b?

    下一篇: 为什么b = b + 1当b是一个字节时不会编译,但b + = 1编译