问题
Today while helping someone I came across an interesting issue which I couldn't understand the reason. While using += we don't need to explicit casting, but when we use i+i, we need to explicitly cast. Couldn't find exact reason. Any input will be appreciated.
public class Test{
byte c = 2;
byte d = 5;
public void test(String args[])
{
c += 2;
d = (byte) (d + 3);
}
}
回答1:
Java is defined such that += and the other compound assignment operators automatically cast the result to the type of the variable being updated. As a result, the cast isn't necessary when using +=, though it is necessary when just using the normal operators. You can see this in the Java Language Specification at http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2
Specifically, the expression
a op= b
Is equivalent to
(a = (type of a)((a) op (b));
Hope this helps!
回答2:
From the Java Language Spec, Chapter 15:
[..] the result of the binary operation (Note:
(c+2)
in our example, which results in anint
type value) is converted to the type of the left-hand variable (Note: tobyte
in our example), 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.
来源:https://stackoverflow.com/questions/9578475/interesting-observation-on-byte-addition-and-assignment