| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Java FAQ:
Why sometime the compound assignment operators don't work the way as expected?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
Is 'x+=a' always equivalent to 'x=x+a'?The answer is not always. Let's start with the following example:
public class Program {
public static void main(String [] args){
int x = 1;
int y = 1;
System.out.println(x += 1);
System.out.println(y = y + 1);
}
}
output 2 2 In this case, x+=a is the same as x=x+a. Let's look at another example:
public class Program {
public static void main(String [] args){
short x = 1;
short y = 1;
System.out.println(x += 1);
System.out.println(y = y + 1); // compile error
}
}
You get a compile time error at y=y+1. Why x+=1 compiles but not y=y+1? "short y =1; y = y + 1;" doesn't compile is because of the so called Binary Numeric Promotion. The operator '+' does the binary numeric promotion to its operands, using Widening Conversion to convert operands as necessary. For y = y + 1, 1 is int, so y is converted to an int, the result of y + 1 is also of type int. But y is declared as of type short, you can't assign an int to a short without explicit casting. This causes compile time error. "short x =1; x += 1;" compiles is because that the compound-assignment operator, '+=', converts the result to the type of the left-hand variable implicitly. That is: short x = 1; x += 1; is actually short x = 1; x = (short)(x + 1); You need cautiously use the compound-assignment operator, since the compiler does the implicit conversion without warning. In a Narrowing conversions case, the conversion may lose information about the overall magnitude of a numeric value and may also lose precision. Do you know what the output is from the following code?
public class Program {
public static void main(String [] args){
byte x = 100;
System.out.println(x += 100);
}
}
|