Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange "for(;;)" infinite loop in Java, how is this useful? [duplicate]

Though I have some experience in Java, the following code looks a bit strange to me:

public class ForLoopTest{
    public static void main(String[] args){
        for(;;){}
    } 
}

This code compiles fine, although the initialization-test-increment part is empty, unlike a usual for loop:

for(int i=0; i<10; i++){}

Since the code compiles fine, it's valid syntax.

Is there any practical use of this type of for loop where there is no initialization-test-increment part ?

like image 964
Razib Avatar asked May 08 '15 13:05

Razib


People also ask

How to write infinite loop in Java?

Infinite loop means a loop that never ends. In this tutorial, I will show you how to write an infinite loop in Java using for and while loop. ‘while’ loop first checks a condition and then runs the code inside its block. We can make it an infinite loop by making the condition ‘true’ :

Why is the value of I printed infinite times in Java?

value of i is printed infinite times ( infinite loop in java occurs) If c oder forgot to increment value of i then value always remains 1 and hence while will evaluate to true. Thus the loop body will keep on executing for infinite times. And we get to see infinite while loop in java. How to avoid infinite loop in java?

Can a for loop always evaluate to true in Java?

Example – Java Infinite For Loop with Condition that is Always True Instead of giving trueboolean value for the condition in for loop, you can also give a condition that always evaluates to true. For example, the condition 1 == 1 or 0 == 0is always true.

Is it a programming error to use infinite loops?

This would probably be a programming error. But using infinite loops can also be intentional according to the requirements of a program. An elegant way of writing infinite loops are given below. for (;;) { // statements or expressions to be executed. } // statements or expressions to be executed.


1 Answers

This is one way of writing an infinite loop. It's equivalent to:

while(true){ }


Or:

boolean loop = true;
while (loop) {
    //do nothing
}

Or even:

int theAnswerToTheQuestionOfLifeTheUniverseAndEverything = 42;
while(theAnswerToTheQuestionOfLifeTheUniverseAndEverything == 42) { 
    //do nothing
} 

​​​​​​​​​​​​​​​​​​​​​​​​

like image 120
JonasCz Avatar answered Sep 29 '22 18:09

JonasCz