Boolean comparison ints when RHS == Integer.MAX_VALUE, why does this loop end?

I am trying to understand why this cycle ends ...

@Test public void test() { int counter=0; int from = 0; int until = Integer.MAX_VALUE; while(counter <= until) { counter++; if(counter < from) { System.out.println("continuing " + counter + " <= " + from); continue; } } System.out.println("finished " + counter); } 

while(counter <= until) should always be true , because the counter cannot be incremented beyond Integer.MAX_VALUE. Thus, the cycle should not end.

However, in Eclipse, if I run with a JUnit runner, I get:

 finished 108772 

If I run in the debugger, I get:

 finished 125156 

The output in if(counter < from) never output. If I delete this block, the code will still exit, this time in Integer.MAX_VALUE.

 finished 2147483647 
+4
source share
2 answers

not quite sure what you are trying to do here, your while loop will work as expected, but from will never change, so the "counter less than from" will never be executed?

before (max int) will be = 2147483647

if you change the while loop to (counter <until), you will get the output text "finished 2147483647"

which help?

0
source

I cannot reproduce your result, so this is not an answer, just an observation. We consider only these lines.

 int counter=0; int until = Integer.MAX_VALUE; while(counter <= until) { counter++; 

The while condition is equal to less than or equal to EQUAL. Therefore, when the counter is Integer.MAX_VALUE, one is added to it. This gives the largest possible negative Java number. Keep adding one to this value, and it will eventually become zero, and then count again until it reaches Integer.MAX_VALUE. Then the whole sequence starts again. It looks endless to me.

You also run the continue line at each iteration when counting from the largest negative number.

0
source

All Articles