Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
3  
The second loop is endless because the upper bound x grows faster than the loop variable j. In other words, j will never hit an upper bound, hence the loop will run "forever." Well, not forever, you'll get an overflow at some point most likely. – Tim Biegeleisen yesterday
47  
It's not an endless loop, it's just that it takes 238609294 times to loop to come out of the for loop in the first case and the second time it prints the value of y 238609294 times – N00b Pr0grammer yesterday
6  
one word answer: overflow – qwr 23 hours ago
4  
Amusingly, System.out.println(x) instead of y at the end would have showed instantly what the problem was – JollyJoker 18 hours ago
6  
@TeroLahtinen no, it would not. Read the Java language spec if you have doubts what is int type. It is hardware independent. – 9ilsdx 9rvj 0lo 17 hours ago
up vote 87 down vote accepted

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.

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

share|improve this answer
25  
I just tried a program (on my laptop) that prints a line in a loop. I timed it, and it was able to print approximately 1000 lines/second. Based on N00b's comment that the loop will execute 238609294 times, it will take about 23861 seconds for the loop to terminate--over 6.6 hours. A tad more than "several minutes". – ajb yesterday
8  
@ajb: Depends on the implementation. IIRC println() on Windows is a blocking operation, whereas on (some?) Unix it's buffered so goes much faster. Also try using print(), which buffers until it hits a \n (or the buffer fills, or flush() is called) – BlueRaja - Danny Pflughoeft 20 hours ago
4  
Also it depends on the terminal showing the output. See stackoverflow.com/a/21947627/53897 for an extreme example (where the slowing down was due to word wrapping) – Thorbjørn Ravn Andersen 11 hours ago
    
Yes, it's buffered on UNIX, but it's still blocking. Once the 8K or so buffer fills, it will block until there's room. The speed will be heavily dependent on how quickly it's consumed. Redirecting output to /dev/null will be the fastest, but having it sent to the terminal, the default, will require graphics updates to the screen and much more compute power as it renders the fonts slowing it down. – penguin359 9 hours ago
    
@penguin359 : that's absolutely correct, terminal will definitely slow it down terribly. About the file - the buffer is flushed to system call only and the OS has is own buffers which are big enough to cache the full output so I wouldn't expect significant slowdown. – Zbynek Vyskovsky - kvr000 1 hour ago

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

share|improve this answer
12  
People don't realise how much spamming to the console can slow their code down. – user9993 14 hours ago

There can be two reasons for this:

  1. Java optimizes the for loop and since there is no use of x after the loop, simply removes the loop. You can check this by putting System.out.println(x); statement after the loop.

  2. It may be possible that Java is not actually optimizing the loop and it is executing the program correctly and eventually x will grow too large for int and overflow. Integer overflow will most probably make the integer x as negative which will be smaller than j and so it will come out of the loop and print the value of y. This also can be checked by adding System.out.println(x); after the loop.

Also, even in the first case eventually overflow will happen thus rendering it to the second case so it will never be a true endless loop.

share|improve this answer
9  
I choose door number 2. – Robby Cornelissen yesterday
    
True. It went on the negative scale and exited the loop. But a sysout is so slow to add an illusion of an infinite loop. – Pavan Kumar yesterday
    
1. Would be a bug. Compiler optimizations are not allowed to change the behavior of a program. If this was an infinite loop, then the compiler may optimize all it wants, however, the result must still be an infinite loop. The real solution is that the OP is mistaken: neither of the two is an infinite loop, one just does more work than the other, so it takes longer. – Jörg W Mittag 14 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.