Phase 5 of 20 · Topic 5.2

Loops: while, do-while, for & Enhanced For-Each

1Concept

Java provides 4 loop constructs: `for` (counted iteration), `while` (pre-condition check), `do-while` (post-condition check guaranteeing at least 1 execution), and enhanced `for-each` (clean traversal over arrays and Collections implementing java.lang.Iterable).

2Architecture Diagram

Enhanced For Loop:
for (String item : items)
       |
       v Compiles into bytecode:
Iterator<String> it = items.iterator();
while (it.hasNext()) { String item = it.next(); ... }

3Code Example

Core Java
import java.util.List;

public class LoopMechanicsDemo {
    public static void main(String[] args) {
        List<String> microservices = List.of("Auth-Service", "Order-Service", "Payment-Service");

        System.out.println("=== Enhanced For-Each Loop Iteration ===");
        for (String service : microservices) {
            System.out.println("Status: Healthy -> " + service);
        }

        System.out.println("\n=== Do-While Guaranteed Execution ===");
        int retryCount = 0;
        do {
            System.out.println("Attempting database connection... (Attempt: " + (retryCount + 1) + ")");
            retryCount++;
        } while (retryCount < 1);
    }
}

4Expected Output

=== Enhanced For-Each Loop Iteration ===
Status: Healthy -> Auth-Service
Status: Healthy -> Order-Service
Status: Healthy -> Payment-Service

=== Do-While Guaranteed Execution ===
Attempting database connection... (Attempt: 1)

5Key Takeaways

  • Do-while loops check conditions after the loop body, guaranteeing execution at least once.
  • Enhanced for-each loop cannot modify elements or remove items during iteration (throws ConcurrentModificationException).
  • Use explicit Iterator.remove() if you need to remove items while looping.