Java打破了强类型!谁能解释一下?
可能的重复:
可能导致精度损失的不同行为
我发现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.
谁能给我解释一下吗?这是一个已知的错误,还是期望的行为? C++ 给出警告,C# 给出编译错误。
Java 会破坏强类型吗? 您可以将 += 替换为 -= 或 *= - 编译器可以接受所有内容。
Possible Duplicate:
Varying behavior for possible loss of precision
I found an inconsistence in Java strong typing check at compile time.
Please look at the following code:
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.
Can anyone explain it to me? Is it a known bug, or desired behavior?
C++ gives a warning, C# gives a compile error.
Does Java breaks strong typing?
You can replace += with -= or *= - everything is acceptable by a compiler.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这种行为是由语言定义的(因此是可以的)。来自JLS:
This behaviour is defined by the language (and is therefore OK). From the JLS:
它可以编译,因为编译器正在转换
为
It compiles because the compiler is converting
to
这与强类型无关,而仅与隐式转换的不同规则有关。
您在这里看到的是两个不同的运算符。在第一种情况下,您有简单的赋值运算符“=”,它不允许将
double
分配给int
。在第二种情况下,您有复合赋值运算符“+=”,它允许通过将double
转换为double
来将double
添加到int
首先是int
。This has nothing to do with strong typing but only with different rules for implicit conversions.
You are looking at two different operators here. In the first case, you have the simple assignment operator "=" which does not allow assigning a
double
to anint
. In the second case, you have the compound assignment operator "+=" which allows adding adouble
to anint
by converting thedouble
to anint
first.