Search code examples
javaloopsfor-loopjvmbytecode

Why does this Java for loop terminate although it is supposed to loop infinitely?


The following loop is supposed to be looping endlessly, or so I think.

int y=0;
for(int x=1; x>0; x++)
{
    y=y+x;
}

However, the loop does terminate, and I do not know why.


Solution

  • Eventually x will be greater than Integer.MAX_VALUE and then it will overflow to negative Here is a quick test to show you what I mean

    int val = 1000000;
    
    for (int i = 0; i < 100; i++) {
         val = val * val;
         if (val < 0) {
             System.out.println(val);
         }
    }