Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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.

like image 604
Madushanka Sampath Avatar asked Jun 19 '16 07:06

Madushanka Sampath


People also ask

What is the difference between b += 1 and b + 1?

Show activity on this post. 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.

What is the difference between int and byte in C?

Note that int is 32 bit and hence its value ranges between -2^31 and (2^31-1). whereas byte is 8 bit and its value ranges from -128 to 127. So explicit cast from int to byte is rarely safe

Why does B=B+1 get an incompatible types exception when adding two types?

In contrast, when you use b=b+1 you are adding two different types and therefore you'll get an Incompatible Types Exception. Show activity on this post. the Error you get is because of the operations with different data types and that can cause an overflow.

What is the difference between ++B and-128 in C++?

that is -128 because the most significant bit for the byte variable is the sign bit. In fact in the last statement (b+1) is upgraded to int while ++b is not. How talented do you have to be to get an interview with Google? , InterviewKickstart.com. Prev: Director of Engineering @ Box. Worked @ MSFT, eBay


2 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.

like image 193
Yar Avatar answered Sep 28 '22 16:09

Yar


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); 
like image 37
ΦXocę 웃 Пepeúpa ツ Avatar answered Sep 28 '22 15:09

ΦXocę 웃 Пepeúpa ツ