Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 378
Omar Avatar asked Feb 01 '17 04:02

Omar


People also ask

Can we use system out Println in for loop?

out. println is not synchronized, that's why the output appears only after the loop is over.

What is a endless loop in Java?

Simply put, an infinite loop is an instruction sequence that loops endlessly when a terminating condition isn't met. Creating an infinite loop might be a programming error, but may also be intentional based on the application behavior.

How do you stop an infinite loop from running in Java?

Just type break; after the statement after which you want to break the loop.


2 Answers

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.

like image 162
Zbynek Vyskovsky - kvr000 Avatar answered Sep 19 '22 17:09

Zbynek Vyskovsky - kvr000


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).

like image 44
Ace Zachary Avatar answered Sep 19 '22 17:09

Ace Zachary