Java For Loop

Java For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop.

Syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Standard for Loop

The example below will print the numbers 0 to 4.

For Loop Example

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

Example explained:


For-Each Loop (Enhanced For Loop)

There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other collections).

Syntax:

for (type variableName : arrayName) {
  // code block to be executed
}

The following example outputs all elements in the cars array, using a "for-each" loop.

For-Each Loop Example

public class Main {
  public static void main(String[] args) {
    String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
    for (String car : cars) {
      System.out.println(car);
    }
  }
}

The for-each loop is generally more readable and less error-prone than a standard for loop when you just need to iterate over all elements of a collection.