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.
Answer
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
.
No comments:
Post a Comment