An interesting problem. In fact, in both cases, the cycle is not infinite.
But the main difference between them is when it will end and how long x will take the value of max int , which is 2,147,483,647 , after which it will reach the overflow state and the cycle will end.
The best way to understand this problem is to check a simple example and save its results.
An example :
for(int i = 10; i > 0; i++) {} System.out.println("finished!");
Output:
finished! BUILD SUCCESSFUL (total time: 0 seconds)
After testing this endless loop, it will take less than 1 second to complete.
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)
In this case, you will notice a huge difference in the time spent on the termination and completion of the program.
If you do not have patience, you will think that this cycle is endless and will not be completed, but in fact, it will take from several hours to i to complete and reach the overflow state.
Finally, we finished after we put the print statement inside the for loop, which in the first case would take much longer than the loop without the print instruction. A.
The time taken to execute the program depends on your technical specifications of the computer, in particular on the processor power (processor), the operating system, and your development environment that compiles the program.
I check this case for:
Lenovo 2.7 GHz Intel Core i5
OS: Windows 8.1 64x
IDE: NetBeans 8.2
It takes about 8 hours (486 minutes) to complete the program.
You may also notice that the step step in the for i = i + 1 loop is a very slow factor to achieve max int value.
We can change this coefficient and take a step with a step faster to check the cycle 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 can see, this is very fast compared to the previous cycle.
less than 1 second is required to complete and complete the program.
After this test case, I think he should clarify the problem and prove the reliability of the answer of Zbynek Vyskovsky - kvr000 , and this will be the answer to this question .