Why sometime the compound assignment operators don't work the way as expected?
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);
}
}
see Xyzws Java FAQ: How do compound assignment operator work for byte primitives?
Most Recent java Faqs
- How to avoid an java.util.ConcurrentModificationException with ArrayList?
- How to convert a given array to a list in Java?
- How to make Java objects eligible for garbage collection?
- What are local variables in Java?
- What are instance variables in Java?
- How many backslashes?
- What are class variables in Java?
Most Viewed java Faqs
- How to use HttpURLConnection POST data to web server?
- What is runtime polymorphism in Java?
- How to add BASIC Authentication into HttpURLConnection?
- What is String literal pool?
- Can the run() method be called directly to start a thread?
- What does Class.forname method do?
- How to read input from console (keyboard) in Java?