Seemingly endless loop terminates, unless System.out.println is used
I had a simple bit of code that was supposed to be an endless loop since x
will always be growing and will always remain larger than j
.
int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
x = x + y;
}
System.out.println(y);
but as is, it prints y
and does not loop endlessly. I cannot figure out why. However, when I adjust the code in the following manner:
int x = 5;
int y = 9;
for (int j = 0; j < x; j++) {
x = x + y;
System.out.println(y);
}
System.out.println(y);
It becomes an endless loop and I have no idea why. Does java recognize its an endless loop and skip it in the first situation but has to execute a method call in the second so it behaves as expected? Confused :)
Both of the examples are not endless.
The issue is the limitation of int
type in Java (or pretty much any other common language). When the value of x
reaches 0x7fffffff
, adding any positive value will result in overflow and the x
becomes negative, therefore lower than j
.
The difference between the first and second loop is that the inner code takes much more time and it would take probably several minutes until x
overflows. For the first example it may take less than second or most probably the code will be removed by optimizer as it doesn't have any effect.
As mentioned in the discussion, the time will heavily depend on how OS buffers the output, whether it outputs to terminal emulator etc., so it can be much higher than few minutes.
Since they are declared as int, once it reaches the max value, the loop will break as the x value will becomes negative.
But when the System.out.println is added to the loop, the speed of execution becomes visible (as outputting to console will slow down the execution speed). However, if you let the 2nd program (the one with syso inside the loop) runs for long enough, it should have the same behavior as the first one (the one without syso inside the loop).