Is a += b really equivalent to a = a + b?
This question already has an answer here:
According to Java Language Specification, section 15.26.2, compound assignment operators insert an implicit conversion to the type of the left-hand side operand:
The result of the binary operation is converted to the type of the lefthand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
An assignment a = a + b
would require a cast to be equivalent:
a = (int)(a + b);
You have a double and int value:
a += b is equivalent to a = (int)(a + b);
a = a + b is equivalent to a = a + b;
in the latter you can't compile because you are trying to add a double to an int without casting. a += b does the cast for you.
链接地址: http://www.djcxy.com/p/12796.html上一篇: Java + =运算符?