关于java:Primitives float和double:为什么f + = d不会导致类型不匹配错误?

Primitives float and double: why does f+=d not result in Type Mismatch Error?

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
Java += operator

代码实例:

1
2
3
4
    double d = 1;
    float f = 2;
    f += d;  // no error?
    f = f+d; // type mismatch error, should be f = (float) (f+d);

为什么不让f+=d制造误差(不安甚至在运行时),这将减少的影响,虽然在d学院吗?


根据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.

这意味着:

1
f += d;

将成为

f = (float) (f+d);


compount赋值执行隐式强制转换。

1
a #= b;

等于

1
a = (cast to type of a) (a # b);

另一个例子

1
2
3
char ch = '0';
ch *= 1.1; // same as ch = (char)(ch * 1.1);
// ch is now '4'


有一篇关于这个主题的好文章:Java+=和隐式铸造