Java ยท Chapter 16 of 42

Java For Loop

The for loop is used when the number of iterations is known ahead of time. It combines initialization, condition, and increment into a single line.

Java also has a for-each loop (enhanced for loop) for iterating directly over arrays and collections without managing an index.

Syntax
for (int i = 0; i < n; i++) {
}
for (Type item : array) {
}

Classic for loop

`for (init; condition; update)` runs init once, then repeats: check condition, run body, run update.

For-each loop

`for (Type item : collection)` iterates over each element directly, which is simpler and less error-prone than index-based loops.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    for (int i = 0; i < 3; i++) {
      System.out.println(i);
    }
    int[] nums = {10, 20, 30};
    for (int n : nums) {
      System.out.println(n);
    }
  }
}
Output
0
1
2
10
20
30

The classic for loop prints 0-2; the for-each loop prints each array element.

Key points

  • A for loop combines init, condition and update.
  • The for-each loop simplifies iterating over arrays/collections.
  • break exits a loop early; continue skips to the next iteration.
  • For loops are best when the iteration count is known.
๐Ÿ’ก Note: Prefer for-each loops when you don't need the index, for cleaner and safer code.

๐Ÿ“ Quick Quiz

1. What three parts make up a classic for loop header?

2. What does the for-each loop iterate over?

3. What does break do inside a loop?