SyntaxStudy
Sign Up
Java for, while, do-while, and the Enhanced for Loop
Java Beginner 1 min read

for, while, do-while, and the Enhanced for Loop

Java provides four loop constructs. The traditional for loop is best when the number of iterations is known in advance; it combines initialisation, condition, and update in a single header. The while loop checks its condition before each iteration and is appropriate when the number of iterations is not known. The do-while loop always executes its body at least once because the condition is checked after the body. The enhanced for loop (also called the for-each loop) introduced in Java 5 iterates over arrays and any Iterable (such as List, Set, or Map values). It is cleaner and less error-prone than an index-based for loop but does not give you the index, and you cannot modify the underlying array or collection during iteration. The break statement exits the nearest enclosing loop or switch immediately. The continue statement skips the rest of the current iteration and moves to the next. Both accept a label to break or continue an outer loop, a feature useful in nested-loop scenarios such as grid traversal.
Example
import java.util.List;

public class LoopsDemo {

    public static void main(String[] args) {

        // --- Traditional for loop ---
        System.out.print("Squares: ");
        for (int i = 1; i <= 8; i++) {
            System.out.print(i * i + " ");
        }
        System.out.println();

        // --- While loop: read until condition ---
        int n = 1;
        System.out.print("Powers of 2 below 1000: ");
        while (n < 1000) {
            System.out.print(n + " ");
            n *= 2;
        }
        System.out.println();

        // --- Do-while: body runs at least once ---
        int counter = 0;
        do {
            System.out.println("do-while iteration: " + counter);
            counter++;
        } while (counter < 3);

        // --- Enhanced for over an array ---
        int[] primes = {2, 3, 5, 7, 11, 13};
        int sum = 0;
        for (int prime : primes) {
            sum += prime;
        }
        System.out.println("Sum of primes: " + sum);

        // --- Enhanced for over a List ---
        List<String> langs = List.of("Java", "Python", "Kotlin", "Go");
        for (String lang : langs) {
            System.out.println("Language: " + lang);
        }

        // --- break and continue with label ---
        outer:
        for (int row = 0; row < 4; row++) {
            for (int col = 0; col < 4; col++) {
                if (col == 2) continue outer;   // skip rest of inner, advance row
                if (row == 3) break outer;       // exit both loops
                System.out.printf("(%d,%d) ", row, col);
            }
        }
        System.out.println("\nDone.");
    }
}