Interesting problem Actually in both cases loop isn't endless
But the main difference between them is when it will terminate and how much time x
will take to exceed max int
value which is 2,147,483,647
after that it will reach overflow state and the loop will terminate.
Best way to understand this problem is to test a simple example and preserve its results.
Example:
for(int i = 10; i > 0; i++) {}
System.out.println("finished!");
Output:
finished!
BUILD SUCCESSFUL (total time: 0 seconds)
After testing this infinite loop it will take less than 1 second to terminate.
for(int i = 10; i > 0; i++) {
System.out.println("infinite: " + i);
}
System.out.println("finished!");
Output:
infinite: 314572809
infinite: 314572810
infinite: 314572811
.
.
.
infinite: 2147483644
infinite: 2147483645
infinite: 2147483646
infinite: 2147483647
finished!
BUILD SUCCESSFUL (total time: 486 minutes 25 seconds)
On this test case you will notice a huge difference in the time taken to terminate and finish running the program.
If you aren't patience you will think this loop is endless and won't terminate but in fact it will take hours to terminate and reach the overflow state at i
value.
Finally we concluded after we put print statement inside for loop that it will take much more time than loop in the first case without print statement.
That time taken to run the program depends on your computer specifications in particular processing power(processor capacity), operating system and your IDE which is compiling the program.
I test this case on:
Lenovo 2.7 GHz Intel Core i5
OS : Windows 8.1 64x
IDE : NetBeans 8.2
It takes about 8 hours (486 minutes) to finish the program.
Also you can notice that the step increment in the for loop i = i + 1
is very slow factor to reach the max int value.
We can change this factor and make step increment more faster in order to test for loop in less time.
if we put i = i * 10
and test it:
for(int i = 10; i > 0; i*=10) {
System.out.println("infinite: " + i);
}
System.out.println("finished!");
Output:
infinite: 100000
infinite: 1000000
infinite: 10000000
infinite: 100000000
infinite: 1000000000
infinite: 1410065408
infinite: 1215752192
finished!
BUILD SUCCESSFUL (total time: 0 seconds)
As you see it's very fast comparing to the previous loop
it takes less than 1 second to terminate and finish running the program.
After this test example I think it should clarify the problem and proves validity of Zbynek Vyskovsky - kvr000's answer, also it will be answer to this question.