Can a for loop be written to create an infinite loop or is it only while loops that do that?

前端 未结 12 1480
时光取名叫无心
时光取名叫无心 2021-01-17 23:58

Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?

12条回答
  •  心在旅途
    2021-01-18 00:38

    Apart from issues of scope and one other thing, this:

    for(; ; ) {
      
    }
    

    is the same as:

    
    while() {
      
      
    }
    

    As other people have alluded to, in the same way that you can have a while loop without an form or form, you can have a for loop without them:

    while() {
      
    }
    

    is the same as

    for(;;) {
      
    } //Although this is terrible style
    

    And finally, you could have a

    for(;true;) {
      
    }
    

    Now, remember when I said there was one other thing? It's that for loops don't need a test--yielding the solution everyone else has posted:

    for(;;) {
      
    }
    

提交回复
热议问题