Java += 操作符实质

来源:互联网 发布:主流的数据库 编辑:程序博客网 时间:2024/05/25 19:56

今天在github上看到了一个开源项目,里面是在整理并翻译stackoverflow上的热门问题,第一个问题是在讨论 i += j 是否等同于 i = i + j;结论是不等于。论证如下:

如果 int i = 9;  long j = 11;   那么 i = i + j不能编译,但 i += j 却可以编译。说明i += j,实际是等同于 i= (type of i) (i + j);

参照官方文档:http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2     

文档内容:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

short x = 3;x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;x = (short)(x + 4.6);
对复合赋值表达式来说,E1 op= E2 (诸如 i += j; i -= j 等等),其实是等同于 E1 = (T)((E1) op (E2)),其中,T是E1这个元素的类型。

stackoverflow链接 http://stackoverflow.com/questions/8710619/java-operator




原文git地址为:https://github.com/giantray/stackoverflow-java-top-qa/blob/master/contents/java-operator.md

A c

0 0
原创粉丝点击