Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Loops and iteration in Java

Loops and iteration in Java: Java provides while with a pre-test, do-while with a post-test, basic for, and enhanced for translated for arrays or Iterable sources.

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

Syntax

loops

Java provides while with a pre-test, do-while with a post-test, basic for, and enhanced for translated for arrays or Iterable sources.

Use enhanced for to read a whole sequence, basic for when an index matters, and Iterator for controlled removal during traversal.

Structural mutation of an ordinary collection inside enhanced for may throw ConcurrentModificationException; assigning the loop variable does not replace the source element.

for(;;) has no condition and is infinite without break or return; continue in a basic for still performs update, and a label can break an outer loop.

The for loop with continue yields for=4, while takes three steps as while=3, do-while runs once as do=1, and Iterator removal leaves remaining=[1, 3].

Examples

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        int oddSum = 0;
        for (int i = 0; i < 5; i++) {
            if (i % 2 == 0) continue;
            oddSum += i;
        }

        int whileCount = 0;
        while (whileCount < 3) whileCount++;

        int doCount = 0;
        do { doCount++; } while (false);

        var values = new ArrayList<>(List.of(1, 2, 3, 4));
        for (var iterator = values.iterator(); iterator.hasNext();) {
            if (iterator.next() % 2 == 0) iterator.remove();
        }
        System.out.println("for=" + oddSum);
        System.out.println("while=" + whileCount);
        System.out.println("do=" + doCount);
        System.out.println("remaining=" + values);
    }
}

Result

for=4
while=3
do=1
remaining=[1, 3]

The for loop with continue yields for=4, while takes three steps as while=3, do-while runs once as do=1, and Iterator removal leaves remaining=[1, 3].

Sources