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);
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With