Lesson 16 +10 XP

Java For Loop

Java For Loop

A for loop repeats a block a known number of times. It is ideal when you know exactly how many iterations you need.

For loop syntax

for (statement 1; statement 2; statement 3) {
  // code block
}
  • Statement 1 runs once before the loop starts.
  • Statement 2 defines the condition that keeps the loop running.
  • Statement 3 runs after each loop block.
for (int i = 0; i < 5; i++) {
  System.out.println(i);
}

This prints 0 1 2 3 4.

For each loop

The enhanced for loop (for each) runs through arrays or collections without a counter:

String[] cars = {"Volvo", "BMW", "Ford"};
for (String i : cars) {
  System.out.println(i);
}

Choosing between loops

  • Use for when you know how many times to repeat.
  • Use for each when iterating over arrays or collections.
  • Use while when you loop until a condition changes.

TL;DR

  • The for loop has three parts: start, condition, and update.
  • The for each loop iterates over arrays and collections.
  • i++ is the common way to step forward by one.