2

Can someone explain what is the condition for this for loop?

for(;;) {
 //do sth.
}
Eran
  • 387,369
  • 54
  • 702
  • 768
user3280180
  • 1,393
  • 1
  • 11
  • 27

8 Answers8

8

It has no condition. It's an infinite loop.

Eran
  • 387,369
  • 54
  • 702
  • 768
2

If the test condition is empty (and it is here), there is no test and the loop continues indefinitely. It's a short form for an infinite loop.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

It is an infinite loop as the condition is empty.

From the java specs If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement. As you don't have condition and break so your its an infinite loop.

NewUser
  • 3,729
  • 10
  • 57
  • 79
2

This is an infinite for loop with no condition. The for loop contains following semantics

for(loop variable initialization ; condition to terminate ; variable increment)

Since there is nothing in between then two ';'its no condition infinite loop

Parth Satra
  • 513
  • 2
  • 16
2

It is equal to this:

while(true){
 //do sth.
}

which is an infinite loop.

Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
2

If you tries to decompile this simple program

for(;;){
    System.out.println("yes");
}

You will get this one as result:

do
   System.out.println("yes");
while(true);

I'm using this decompile tool: JAD Java Decompiler (dont work for Java 8+)

alex
  • 8,904
  • 6
  • 49
  • 75
1

The three expressions of the for loop are optional, an infinite loop can be created as follows:

// Infinite loop
for ( ; ; ) {
   // Your code goes here
}
Bence Kaulics
  • 7,066
  • 7
  • 33
  • 63
Harshal
  • 126
  • 7
1

As everyone said, it is an infinite loop. A simple way to see that it is an infinite loop is to look the for(;;) statement in byte code.

Take this reference class:

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

The compiler output (in bytecode):

public class Test {
  public Test();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        

  public static void main(java.lang.String[]);
    Code:
       0:
         goto 0
}

The goto 0 jumps at the label 0, which is above line. This process will never stops.

Pier-Alexandre Bouchard
  • 5,135
  • 5
  • 37
  • 72