3

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?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Srikanth Ganji
  • 1,127
  • 1
  • 13
  • 29

2 Answers2

17

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks a lot. Yeah It was so silly that I was expecting heap memory exception instead of stack over flow error. But now I came to know why it was not running in an infinite loop and why there are no errors. – Srikanth Ganji Jan 13 '14 at 07:28
  • @SrikanthGanji: Why would you even expect a stack overflow? No more stack memory is being allocated within the loop either - it's just replacing one value with another. – Jon Skeet Jan 13 '14 at 09:30
4

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.

Ken
  • 30,811
  • 34
  • 116
  • 155