Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

for — basic and enhanced loops

for — basic and enhanced loops: The for statement is either basic with initialization, condition, and update, or enhanced for, which successively assigns elements from an array or Iterable.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

for

The for statement is either basic with initialization, condition, and update, or enhanced for, which successively assigns elements from an array or Iterable.

Use basic for when an index or step matters, and enhanced for when elements matter without explicit iterator control.

An omitted basic-for condition means true; structurally changing a collection outside its iterator during enhanced for can cause ConcurrentModificationException.

The enhanced-for source expression is evaluated once; a null array or Iterable causes NullPointerException, as can unboxing a null element to a primitive.

The basic for adds 1, 2, and 3 to produce sum=6; enhanced for traverses a and b, so the second line is letters=ab.

Examples

import java.util.List;

public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1; i <= 3; i++) sum += i;
        StringBuilder letters = new StringBuilder();
        for (String letter : List.of("a", "b")) letters.append(letter);
        System.out.println("sum=" + sum);
        System.out.println("letters=" + letters);
    }
}

Result

sum=6
letters=ab

The basic for adds 1, 2, and 3 to produce sum=6; enhanced for traverses a and b, so the second line is letters=ab.

Sources