Java += 操作符实质

今天在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

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值