简体   繁体   English

for循环在与Integer.MAX_VALUE和使用System.out.println进行比较时提前终止

[英]for loop terminating early when comparing to Integer.MAX_VALUE and using System.out.println

When I run this class the for loop seems to terminate early 当我运行这个类时,for循环似乎提前终止

class Test {

    public static void main(String[] args) {
        int result = 0;
        int end = Integer.MAX_VALUE;
        int i;
        for (i = 1; i <= end; i += 2) {
            System.out.println(i);
        }
        System.out.println("End:" + i);
    }

}

Output is: 输出是:

1
3
5
...
31173
31175
End:31177

Why does it end there? 为什么它会在那里结束? Interestingly if I removed the System.out.println(i) in the for loop, the output would be End:-2147483647 . 有趣的是,如果我在for循环中删除了System.out.println(i) ,输出将为End:-2147483647 Obviously the value in i has wrapped round . 显然, i的价值已经wrapped round

The Java version I'm using is 我正在使用的Java版本是

Java(TM) SE Runtime Environment (build 1.6.0_16-b01)
Java HotSpot(TM) 64-Bit Server VM (build 14.2-b01, mixed mode)

Its a known bug in Java 6. The JIT optimizes the loop incorrectly. 它是Java 6中的一个已知错误.JIT错误地优化了循环。 I believe more recent versions of Java don't have this bug. 我相信更新的Java版本没有这个bug。

http://vanillajava.blogspot.co.uk/2011/05/when-jit-gets-it-wrong.html http://vanillajava.blogspot.co.uk/2011/05/when-jit-gets-it-wrong.html

Java 6 update 16 is just over two years old. Java 6更新16刚刚超过两年。 I suggest you update to the latest version Java 6 update 25 if you can't update to Java 7. 如果您无法更新到Java 7,我建议您更新到最新版本的Java 6 update 25。

BTW Java 6 will be End Of Free Support in a couple of months (Dec 2012) BTW Java 6将在几个月内完成免费支持(2012年12月)

您可以使用Integer.MAX_VALUE-1解决JVM错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM