Question

Like many other question explained that while(true) {} is an infinite loop and so is for( ; ;) my question is while(true) makes sense the conditions is always true but there is no vivid condition true/false in for( ; ;) so how is the later an infinite loop.

Was it helpful?

Solution

According to Java Language Specification, section 14.14.1.2:

for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement

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.

Since the standard treats missing expressions and expressions evaluating to true in the same way, the for loop with the missing expression is equivalent to an infinite loop.

OTHER TIPS

You do not specify any condition to continue the loop, so it is executed forever.

The three parts of for loop: variable initialization, condition and variable update are optional. If the condition is absent, it is evaluated as true. The loop continues till something else in for loop block stops it. Since in your example for loop is empty, it is an infinite loop.

A loop becomes infinite loop if a condition never becomes false. The for loop is traditionally used for this purpose. Since none of the three expressions that form the for loop are required, you can make an endless loop by leaving the conditional expression empty. When the conditional expression is absent, it is assumed to be true.

The loop for( ; ;) is garbage. If that provides an infinite loop, it is at the control of that specific languages compiler that turns it into a infinite loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top