Interesting observation on byte addition and assignment

ぃ、小莉子 提交于 2021-02-04 19:06:40

问题


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 an int type value) is converted to the type of the left-hand variable (Note: to byte 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!