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 ?
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’ :
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?
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With