Monday 1 May 2017

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





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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...