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.
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.
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
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.
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
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 toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With