Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

for

A loop with a counter, or iteration over every element of an array or collection (for-each).

Available since: Java 1.0

Syntax

for (init; condition; update) { … }  /  for (Type item : collection) { … }

Examples

A classic loop with a counter:

void main() {
    for (int i = 1; i <= 3; i++) {
        IO.println("step " + i);
    }
}

Output:

step 1
step 2
step 3

for-each — iteration without an index:

void main() {
    List<String> names = List.of("Anna", "Oleg");
    for (String name : names) {
        IO.println("Hi, " + name);
    }
 
    int sum = 0;
    for (int n : new int[] {4, 5, 6}) {
        sum += n;
    }
    IO.println(sum);
}

Output:

Hi, Anna
Hi, Oleg
15

Notes

for-each gives no index, and you cannot remove elements from the collection inside it — you get ConcurrentModificationException. Use removeIf() or an iterator to remove. The counter variable i exists only inside the loop.

See also

  • while / do-while — Repeats a block while a condition is true; do-while runs it at least once.
  • break / continue — break exits a loop, continue jumps to the next iteration; a label lets you leave a nested loop.
  • array.length — The length of an array — the number of elements. A field, not a method: no parentheses.

Related recipes

In the tutorial

  • Loops — Loops in Java: while, do-while, for and for-each over an array.

Thanks for reading!

Donate to the site — we work hard for you.