Java for loop variations

Introduction

The Java for loop can have a number of variations.

Its three parts-the initialization, the conditional expression, and the iteration-are all optional.

The following code uses for loop as a while loop

// Parts of the for loop can be empty.
public class Main {
  public static void main(String args[]) {
    int i;/*w  w w .ja v  a 2s  .co m*/
    boolean done = false;

    i = 0;
    for( ; !done; ) {
      System.out.println("i is " + i);
      if(i == 10) done = true;
      i++;
    }
  }
}

Here, the initialization and iteration expressions were removed from for loop.

You leave all three parts of the for empty. For example:

for( ; ; ) {  
   // ...  
} 



PreviousNext

Related