EMZETT.
Login

For Loop

For-Schleife Image: Bagok, Public domain, Wikimedia Commons

In short: A pre-test loop with a fixed, defined counter — starting value, exit condition, and step size are all in the loop header.

In more detail: Classic syntax: for (int i = 0; i < n; i++) { ... }. Java additionally has the for-each variant (for (Type element : collection) { ... }), which iterates over arrays or collections without maintaining a manual index — convenient, but with no direct access to the index itself.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

In Depth

Structure of the loop header

int[] numbers = {10, 20, 30, 40};
 
// Classic for loop: access to the index itself is possible
for (int i = 0; i < numbers.length; i++) {
    System.out.println("Index " + i + ": " + numbers[i]);
}
 
// For-each variant: shorter, but no access to the index
for (int number : numbers) {
    System.out.println(number);
}

The header of the classic for loop consists of three parts separated by semicolons: initialization (runs exactly once, before the first iteration), condition (checked before EVERY iteration, ends the loop as soon as it returns false), and increment/update (runs after every iteration’s body, before the next condition check). All three parts are optional — for (;;) { ... } is a valid, deliberately infinite loop (equivalent to while (true)), which you’d end e.g. in a server loop with a break at the right spot. Several variables can be initialized/incremented at once with commas: for (int i = 0, j = 10; i < j; i++, j--) — both run synchronously in opposite directions, useful for example to traverse an array from both ends at once (e.g. for a palindrome check).

For-each as syntactic sugar

The for-each variant (for (Type element : collection)) is syntactic sugar over an iterator — the compiler internally translates it into something like Iterator<T> it = collection.iterator(); while (it.hasNext()) { T element = it.next(); ... }. It’s suitable whenever you simply want to visit EVERY element without needing the index itself, and works with arrays and anything that implements the Iterable interface (so practically all collections like ArrayList, HashSet, LinkedList). An important difference from the index-based loop: removing elements directly from the collection during a running for-each loop throws a ConcurrentModificationException, because the iterator used internally notices the structure has changed “under it” — that instead requires iterator.remove() via an explicit iterator, or you build a separate list of elements to remove and delete them only after the loop.

Typical pitfalls

A classic beginner mistake is the so-called off-by-one problem: i <= numbers.length instead of i < numbers.length leads to an ArrayIndexOutOfBoundsException, because array indices in Java start at 0 and the last valid index is length - 1. Another common mistake is accidentally “shadowing” the same counter variable in nested loops (for (int i = ...) { for (int i = ...) }) — this doesn’t compile, because i already exists in the inner scope, which Java compilers thankfully flag immediately with a clear error message. Caution is also needed with floating-point counters: for (double d = 0.0; d != 1.0; d += 0.1) can theoretically never terminate due to floating-point rounding errors, because d might never hit exactly 1.0 — here you should either compare with < instead of !=, or use an integer counter and only convert within the loop body.

Unlike the while loop, which is primarily meant for conditions with no fixed counter (e.g. “as long as user input isn’t ‘exit’”), the for loop is the natural choice when the number of iterations is known or computable in advance — such as “exactly n times” or “once per element of a list”. All three basic forms (classic, for-each, and the less commonly used combination with break/continue for leaving early or skipping individual iterations) can be converted into each other, but differ noticeably in readability: for-each is usually the shortest and least error-prone form, as soon as the index itself isn’t needed.

See also: Loops, While Loop, Index, Arrays, Break/Continue