Sunday, 25 December 2016

java - 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 :)


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...