For statement in detail : For Loop « Statement Control « Java Tutorial






It is common to declare a variable and assign a value to it in the initialization part. The variable declared will be visible to the expression and update parts as well as to the statement block.

For example, the following for statement loops five times and each time prints the value of i. Note that the variable i is not visible anywhere else since it is declared within the for loop.

public class MainClass {

  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
        System.out.println(i + " ");
    }
  }
}

The initialization part of the for statement is optional.

public class MainClass {

  public static void main(String[] args) {
    int j = 0;
    for (; j < 3; j++) {
      System.out.println(j);
    }
    // j is visible here
  }

}

The update statement is optional.

public class MainClass {

  public static void main(String[] args) {
    int k = 0;
    for (; k < 3;) {
      System.out.println(k);
      k++;
    }
  }

}

You can even omit the booleanExpression part.

public class MainClass {

  public static void main(String[] args) {
    int m = 0;
    for (;;) {
      System.out.println(m);
      m++;
      if (m > 4) {
        break;
      }
    }
  }

}

If you compare for and while, you'll see that you can always replace the while statement with for. This is to say that

while (expression) {
    ...
}

can always be written as

for ( ; expression; ) {
    ...
}








4.6.For Loop
4.6.1.The for Statement
4.6.2.For statement in detail
4.6.3.A loop allows you to execute a statement or block of statements repeatedly
4.6.4.The numerical for loop
4.6.5.Infinite For loop Example
4.6.6.initialization_expression: define two variables in for loop
4.6.7.Declare multiple variables in for loop
4.6.8.Multiple expressions in for loops
4.6.9.To omit any or all of the elements in 'for' loop: but you must include the semicolons
4.6.10.Keeping the middle element only in for loop
4.6.11.Using the Floating-Point Values as the control value in a for loop
4.6.12.Nested for Loop
4.6.13.Java's 'labeled for' loop
4.6.14.Print out a Diamond