+ = int和双转换

时间:2010-05-25 14:00:05

标签: java

  

可能重复:
  Varying behavior for possible loss of precision

int testing = 0;
testing += 2.0

上面的代码编译。

其中

int testing = 0;
testing = testing + 2.0;

此代码无法编译。知道为什么吗?

1 个答案:

答案 0 :(得分:8)

复合赋值在Java中有隐藏的强制转换。

JLS 15.26.2 Compound Assignment Operators

  

E1 op = E2 形式的复合赋值表达式等效于 E1 =(T)((E1)op(E2)),其中 T E1 的类型,但 E1 仅评估一次。

     

例如,以下代码是正确的:

short x = 3;
x += 4.6;
     

并导致x的值为7,因为它等同于:

short x = 3;
x = (short)(x + 4.6);

相关问题