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

余生颓废 提交于 2020-01-29 12:04:48

问题


When I run this class the for loop seems to terminate early

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. Obviously the value in i has wrapped round.

The Java version I'm using is

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

回答1:


Its a known bug in Java 6. The JIT optimizes the loop incorrectly. I believe more recent versions of Java don't have this bug.

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

Java 6 update 16 is just over two years old. I suggest you update to the latest version Java 6 update 25 if you can't update to Java 7.

BTW Java 6 will be End Of Free Support in a couple of months (Dec 2012)




回答2:


You can work around the JVM bug by using Integer.MAX_VALUE-1.



来源:https://stackoverflow.com/questions/12793248/for-loop-terminating-early-when-comparing-to-integer-max-value-and-using-system

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!