Reputation: 35
i had the code:
public static void main(String[] args) {
int i=0;
while(true){
i++;
System.out.println(i); //(1)
if(i==-1){
break;
}
}
}
if has the code (1) ,it will run in endless loop , but if not has code (1),the code cannot run in endlessLoop and has no error just like not have the loop , but if i run in debug model ,it could run in endless loop.
so why it has this result.
my IDE is idea, and java1.8
Upvotes: 0
Views: 88
Reputation: 394016
This code is not an endless loop.
i
will eventually become negative due to integer overflow. It will overflow to Integer.MIN_VALUE
, and eventually will reach -1.
However, when you include that print statement, it takes a long of time to finish (it has to print over 4 billion values of i
), so it appears to be endless.
When you remove the print statement, it becomes much faster.
That said, the compiler might even decide to optimize the entire loop if it decides that the loop does nothing, which will reduce the running time to 0.
You can see that the loop terminates even with the println
statement if you add a condition that prints only few of the values, which will make the execution much faster.
For example, printing once every 100 million values:
public static void main(String[] args) {
int i=0;
while(true) {
i++;
if (i%100000000 == 0) System.out.println(i);
if(i==-1){
break;
}
}
}
will output:
100000000
200000000
300000000
400000000
500000000
600000000
700000000
800000000
900000000
1000000000
1100000000
1200000000
1300000000
1400000000
1500000000
1600000000
1700000000
1800000000
1900000000
2000000000
2100000000
-2100000000
-2000000000
-1900000000
-1800000000
-1700000000
-1600000000
-1500000000
-1400000000
-1300000000
-1200000000
-1100000000
-1000000000
-900000000
-800000000
-700000000
-600000000
-500000000
-400000000
-300000000
-200000000
-100000000
and terminate.
Upvotes: 5
Reputation: 23037
Well, not exactly sure what you mean, but the loop is not endless.
Due to integer overflow, the value of i
will eventually become -1
and the loop will terminate.
It doesn't matter whether you print i
or not. It is just that it takes way longer to write eveything to the console.
Upvotes: 1
Reputation: 7185
Loop will end when i reaches max value (Integer.MAX_VALUE
) as on overflow i will eventually reach to -1 and loop will be terminated.
Upvotes: 1