Duplicate :
|
FULL PRODUCT VERSION : [karel@myhost src]$ java -version java version "1.6.0_21" Java(TM) SE Runtime Environment (build 1.6.0_21-b06) Java HotSpot(TM) Server VM (build 17.0-b16, mixed mode) ADDITIONAL OS VERSION INFORMATION : Linux myhost 2.6.32-24-generic-pae #42-Ubuntu SMP Fri Aug 20 15:37:22 UTC 2010 i686 GNU/Linux EXTRA RELEVANT SYSTEM CONFIGURATION : not important A DESCRIPTION OF THE PROBLEM : Following iteration is terminated randomly (the terminate condition should be never met, the iteration should run indefinitely): public class MaxIntConditionDefect { public static void main(String[] args) { int min = 1; int max = Integer.MAX_VALUE; System.out.println("max = " + max); long counter = 0; int i; for(i = min; i <= max; i++) { counter++; System.out.println("asking for"); } System.out.println("iteration went " + counter + " times (" + i + ")"); System.out.println("max = " + max); } } STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : compile and run the above code EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - I expect the cycle to run indefinitely (just sample...) ACTUAL - one sample: max = 2147483647 asking for asking for ..... asking for asking for iteration went 14563 times (14564) max = 2147483647 another sample: max = 2147483647 asking for asking for ..... asking for asking for iteration went 15587 times (15588) max = 2147483647 ERROR MESSAGES/STACK TRACES THAT OCCUR : no explicit error, just unexpected behavior REPRODUCIBILITY : This bug can be reproduced always. ---------- BEGIN SOURCE ---------- public class MaxIntConditionDefect { public static void main(String[] args) { int min = 1; int max = Integer.MAX_VALUE; System.out.println("max = " + max); long counter = 0; int i; for(i = min; i <= max; i++) { counter++; System.out.println("asking for"); } System.out.println("iteration went " + counter + " times (" + i + ")"); System.out.println("max = " + max); } } ---------- END SOURCE ---------- CUSTOMER SUBMITTED WORKAROUND : I have found a workaround in my case - compare to Integer.MAX_VALUE-1 - in my case it does not matter whether I compare to Integer.MAX_VALUE or Integer.MAX_VALUE-1