Why below code is going for infinite loop? Why is it not throwing compile time error?
public class Main {
public static void main(String[] args) {
for(;;){
System.out.println("while loop");
}
}
}
Why below code is going for infinite loop? Why is it not throwing compile time error?
public class Main {
public static void main(String[] args) {
for(;;){
System.out.println("while loop");
}
}
}
The syntax of a basic for loop is:
BasicForStatement: for ( [ForInit] ; [Expression] ; [ForUpdate] ) Statement
The []
around ForInit
, Expression
and ForUpdate
mean that all of those things are optional.
As such, for (;;) { /* something */ }
is valid syntax, so it would not result in a compile-time error.
Then (emphasis added):
If the Expression is not present, or it is present and the value resulting from its evaluation (including any possible unboxing) is true, then the contained Statement is executed. Then there is a choice:
If execution of the Statement completes normally, then the following two steps are performed in sequence:
First, if the ForUpdate part is present [it's not, so omitting this]
If the ForUpdate part is not present, no action is taken.
Second, another for iteration step is performed.
Expression
is not present, the Statement
completes normally: so another for iteration step is performed.
This is all a way of saying: you've got an infinite loop because there's nothing to stop it continuing to execute.