数字赋值应该抛出错误
我正在用 Java 中的数字转换和强制转换进行一些测试,我发现了这种奇怪的行为(对我来说)
class Test {
public static void main(String[] args) {
//int y = 100000000000000; //does not compile
int x = 100000 * 1000000000; //compile (why?)
System.out.println(x); //x is 276447232
}
}
基本上 x 和 y 应该是相同的数字:为什么它会编译?
I was making some tests with numeric conversions and casts in Java and I found this strange behaviour (for me)
class Test {
public static void main(String[] args) {
//int y = 100000000000000; //does not compile
int x = 100000 * 1000000000; //compile (why?)
System.out.println(x); //x is 276447232
}
}
Basically x and y should be the same number: why does it compile?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Java 中的整数溢出无法被检测到,这就是乘法工作正常的原因。但是,您所说的文字太大,因此是编译器错误。
我猜想虽然绝大多数 Java 编译器会在编译时预先计算该值,但 JLS 并不需要。因此它不可能是一个错误,因为不同的编译器可能会编译一段代码或产生错误——这不太好。
Sun Java 编译器实际上执行反汇编所示的计算:
这里需要注意的重要一点是,对于所有意图和目的,结果必须与在运行时计算的结果相同。因此这里不会发生编译器错误。
Integer overflow goes undetected in Java, that's why the multiplication works fine. However, the literal you were stating was too large and thus is a compiler error.
I guess while the vast majority of Java compilers will precompute that value at compilation time that is not required by the JLS. Thus it cannot be an error, since then different compilers may compile a piece of code or yield errors – something that isn't so nice.
The Sun Java compiler actually performs the calculation as the disassembly shows:
The important thing to note here is that for all intents and purposes the result must be the same as if it were computed during runtime. Therefore no compiler error can occur here.
Java 不是通过异常来处理整数溢出,而是通过翻转为负值并继续向上处理。
作为一个例子,下面是这个代码片段:
Java 尽其所能地处理它。该代码片段输出:
这是 Integer.MIN_VALUE 的值。当你处理非常大的数字时,你必须要小心。这就是为什么 Java 有
BigInteger
类来处理超出整数限制的任意大数字。
Java deals with overflowing an integer not by an exception but by instead flipping over to negative values and continuing upward.
As an example, here's this code snippet:
Java deals with it the best it can. That snippet outputs:
Which is the value of Integer.MIN_VALUE. You just have to be careful when you are dealing with really big numbers. That's why Java has a
BigInteger
class to deal with arbitrarily big numbers that go beyond the limit of integers.