Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 767
Ben Avatar asked Oct 09 '12 05:10

Ben


2 Answers

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)

like image 185
Peter Lawrey Avatar answered Oct 21 '22 11:10

Peter Lawrey


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

like image 37
user2411179 Avatar answered Oct 21 '22 12:10

user2411179