Java for loop statement

Introduction

There are two forms of the for loop.

The first is the traditional form.

The second is the newer "for-each" form.

Here is the general form of the traditional for statement:

for(initialization; condition; iteration) {  
   // body  
} 

The for loop iterates:

  • first evaluating the conditional expression,
  • then executing the body of the loop,
  • and then executing the iteration expression with each pass.

When the loop first starts, the initialization portion of the loop is called.

The initialization sets the value of the loop control variable.

The initialization expression is executed only once.

Then the condition is evaluated. The condition must be a Boolean expression.

If the condition is true, then the body of the loop is executed.

If it is false, the loop terminates.

After that, the iteration is executed.

This process repeats until the controlling expression is false.

Here is a version of the "tick" program that uses a for loop:

// Demonstrate the for loop.
public class Main {
  public static void main(String args[]) {
    int n;//from w  ww .j  a v  a 2 s. c  om

    for(n=10; n>0; n--)
      System.out.println("tick " + n);
  }
}

Declaring Loop Control Variables Inside the for Loop

We can declare the variable inside the initialization portion of the for.

// Declare a loop control variable inside the for.
public class Main {
  public static void main(String args[]) {

    // here, n is declared inside of the for loop
    for(int n=10; n>0; n--)
      System.out.println("tick " + n);
  }//from  w w w. java2s . c  o m
}

The scope of the loop control variable is limited to the for statement.

Using the Comma in for loop

We can use comma to include more than one statement in the for loop initialization and iteration.

For example,


// Using the comma.  
public class Main {  
  public static void main(String args[]) {  
    int a, b;  /*  w  w  w .ja v  a  2  s . c  o  m*/
  
    for(a=1, b=4; a<b; a++, b--) {  
      System.out.println("a = " + a);  
      System.out.println("b = " + b);  
    }  
  }  
} 

Nested for loops

Java loops to be nested.

For example, here is a program that nests for loops:

// Loops may be nested.
public class Main {
  public static void main(String args[]) {
    int i, j;/*from  w w w .jav a2s.c om*/

    for(i=0; i<10; i++) {
      for(j=i; j<10; j++)
        System.out.print(".");
      System.out.println();
    }
  }
}



PreviousNext

Related