Java打破了强大的打字!谁能解释一下?

Mic*_*l P 16 java strong-typing

可能重复:
可能导致精度损失的不同行为

我在编译时发现Java强类型检查不一致.请看下面的代码:

int sum = 0;
sum = 1; //is is OK
sum = 0.56786; //compile error because of precision loss, and strong typing
sum = sum + 2; //it is OK
sum += 2; //it is OK
sum = sum + 0.56787; //compile error again because of automatic conversion into double, and possible precision loss
sum += 0.56787; //this line is does the same thing as the previous line, but it does not give us a compile error, and javac does not complain about precision loss etc.
Run Code Online (Sandbox Code Playgroud)

有谁可以向我解释一下?这是一个已知的错误,或期望的行为?C++发出警告,C#给出了编译错误.

Java打破强打字吗?您可以将+ =替换为 - =或*= - 编译器可以接受所有内容.

McD*_*ell 28

此行为由语言定义(因此可以).来自JLS:

15.26.2复合赋值运算符

形式E1 op = E2的复合赋值表达式等效于E1 =(T)((E1)op(E2)),其中T是E1的类型,除了E1仅被评估一次.例如,以下代码是正确的:

short x = 3;
x += 4.6;
Run Code Online (Sandbox Code Playgroud)

并且结果x的值为7,因为它相当于:

short x = 3;
x = (short)(x + 4.6);
Run Code Online (Sandbox Code Playgroud)

  • 这是经常被忽视的东西,我们倾向于认为+ =只是一个较短的版本,但它确实有其他含义.要记住的好提示. (4认同)
  • @irreputable - 嗯,这是与语言设计师有关的东西; 编译器符合规范. (4认同)

Joh*_*n B 5

它编译是因为编译器正在转换

sum += 0.56787;
Run Code Online (Sandbox Code Playgroud)

sum = (int)(sum + 0.56787);
Run Code Online (Sandbox Code Playgroud)