First of all, both snippets are not infinite loops, since i
will become negative once it passes Integer.MAX_VALUE
. They just take a long time to run.
The first snippet takes much less time to run, since it doesn't have to print anything, and it's possible the compiler is smart enough to just optimize the code and eliminate the loop, since it does nothing.
Testing your first snippet, adding System.out.println (System.currentTimeMillis ());
before and after the loop, I got :
1486539220248
1486539221124
i.e. it ran in less than 1 second.
Changing the loop slightly :
System.out.println (System.currentTimeMillis ());
for(int i = 2; i > 0; i++){
int c = 0;
if (i==Integer.MAX_VALUE)
System.out.println (i);
}
System.out.println (System.currentTimeMillis ());
I got
1486539319309
2147483647
1486539319344
As you can see, it takes i
less than 1 second to increment from 0
to Integer.MAX_VALUE
, and then overflow, at which point the loop terminates.
The more prints you add to the loop, the more time it will take to terminate. For example :
System.out.println (System.currentTimeMillis ());
for(int i = 2; i > 0; i++){
int c = 0;
if (i % 100000000 == 0)
System.out.println (i);
}
System.out.println (System.currentTimeMillis ());
Output :
1486539560318
100000000
200000000
300000000
400000000
500000000
600000000
700000000
800000000
900000000
1000000000
1100000000
1200000000
1300000000
1400000000
1500000000
1600000000
1700000000
1800000000
1900000000
2000000000
2100000000
1486539563232
Now it took 3 seconds.