Question

I have a following code sample

int i = 1;  

while(i != 0) {  
    i++;  
} 

I was expecting this to run in an infinite loop but it didn't. Then when I printed the value after while loop I got:

i value is 0.  

Can any one let me know what exactly is happening?

Was it helpful?

Solution

I was expecting this to run in an infinite loop but it didn't.

No, it wouldn't. Eventually the value will become 0 again.

In particular, it will logically execute like this:

1
2
3
...
2,147,483,646
2,147,483,647  
-2,147,483,648  // Integer overflow => wrapping
-2,147,483,647
...
-3
-2
-1
0

... then the loop will end

From section 15.18.2 of the JLS:

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

There are no memory issues with this code because it doesn't perform any allocations - it just increments a local variable, entirely on the stack.

Now whether or not it actually does that is a different matter - if the JIT is able to work out what the behaviour will be without executing every iteration, it can optimize it away - but that's an implementation detail. The important part is understanding the logic behind the behaviour.

OTHER TIPS

An int is an int: For each i, if i is an int so is i+1. An int is always 32-bits, it never requires a larger container.

Last, your loop is not infinite.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top