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 uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?