Consider the following java code:
public int main() {
int i = 1111;
for (; rules(i) != true && i < Integer.MAX_VALUE; i++) {
//LOG.debug("Testing i: " + i);
}
System.out.println("The mystery number is: " + i);
return i;
}
protected boolean rules(int nb) {
//...
}
I've found out that even when the for loop continuation evaluation is true
, the loop will stop being executed when its body is empty.
The final result of main
is wrong (i
is 16698 about 98% of the time and sometimes a little higher/lower).
If I uncomment the LOG statement from the loop body, the loop will keep on running until the loop continuation evaluation is false
.
The JVM I'm using is MacOS X VM 1.6.0.
- Is it doing some sort of runtime optimization?
- Can this runtime optimization be considered a bug?
- Or is it said somewhere in Java specs that for continuation evalution should not run functional operations?
ps: the full code source + its unit test are available here: https://gist.github.com/dirtyhenry/5804130
UPDATE:
- I've run the code via junit only. Could junit be responsible for this behavior?
UPDATE 2:
java -version
returns:
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-456-11M4508)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-456, mixed mode)
int
tolong
. Maybe there is a silent value overflow. - spasint
tolong
and keeping an empty loop, i get the right result. Funny though, cause 16698 is very far from the maximal value of int in Java (2147483647, cf. docs.oracle.com/javase/tutorial/java/nutsandbolts/…) - Dirty Henry