简体   繁体   中英

please explain, Why the below code is going to infinite 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:

  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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM