5

This is my code:

class Example{
    public static void main(String args[]){
        byte b=10;
        //b=b+1; //Illegal
        b+=1;   //Legal
        System.out.println(b);
    }
}

I want to know why I'm getting a compilation error if I use b=b+1, but on the other hand b+=1 compiles properly while they seem to do the same thing.

Tunaki
  • 125,519
  • 44
  • 317
  • 399

3 Answers3

5

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.

Yar
  • 6,330
  • 10
  • 43
  • 62
1

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); 
ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
0

Because can't convert int to byte

You can try:

b=(byte) (b+1);

ThiepLV
  • 1,169
  • 3
  • 9
  • 21