-1

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");
       }
    }
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Bhuvan
  • 23
  • 5
  • 3
    Because it's legal code, and it expresses an infinite loop. – Andy Turner Sep 11 '19 at 10:53
  • The for loop iteration stops once the condtion (after first ; in for loop) is not satisfied. In the above Code there is no Condition to statisfy and is true by default. So this code will run as a infinite loop. – Sujay Mohan Sep 11 '19 at 10:53
  • See also [Java: for(;;) vs. while(true)](https://stackoverflow.com/q/8880870), and why some people prefer it https://stackoverflow.com/a/2611529 (although this answer is based on C++). – Pshemo Sep 11 '19 at 11:00

1 Answers1

1

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:

  1. 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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243