I wrote the following code, which answers differently when I have printing statement and without it.
class test
{
public static void main(String args[])
{
int i = Integer.MAX_VALUE;
int j = Integer.MAX_VALUE-100;
int count = 0;
for(; j<=i; j++){
count++;
//System.out.println(j); // If we remove comment, answer is different
}
System.out.println(count + ", " + j + ", " + (j<=i));
}
}
The answer without print statement is :
101, -2147483648, true
and with print statement is :
15588, -2147468161, true
In both the cases, the final condition should return false, but it returns true. Can anybody explain this.
j <= Integer.MAX_VALUEis always true by definition. Your loop never ends, in both cases.If you change this to
j < i, the loop will terminate and the same answer will be returned regardless of the print statement.EDIT
When testing the code with Netbeans / Oracle JDK 7u9, the loop never ends as expected. However some report that they see the same behaviour as described in the question. @auselen points to this similar post which refers to a bug.