For a loop ending earlier by comparing with Integer.MAX_VALUE and using System.out.println

When I run this class, the for loop seems to end the 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); } } 

Exit:

 1 3 5 ... 31173 31175 End:31177 

Why does it end? Interestingly, if I deleted System.out.println(i) in a for loop, the output would be End:-2147483647 . Obviously, the value in i is wrapped round .

The used version of Java 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) 
+8
java max int for-loop
source share
2 answers

Its a known bug in Java 6. JIT does not optimize the loop correctly. I believe that more recent versions of Java do not have this error.

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

Update for Java 6 updated to two years. I suggest you upgrade to version 25 to update the latest version 25 if you cannot upgrade to Java 7.

BTW Java 6 will become free support in a couple of months (December 2012)

+15
source share

You can work with JVM error using Integer.MAX_VALUE-1.

+1
source share

All Articles