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)
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)
You can work around the JVM bug by using Integer.MAX_VALUE-1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With