Skip to content
UniCircle
EasyConceptualControl flow

while vs do-while vs for-each

Question JAVA-OPS-007

When would you choose a do-while loop over a while loop? What are the limits of the enhanced for (for-each) loop?

Show the explanation

A while loop checks its condition before each pass, so its body may run zero times. A do-while checks after, so the body always runs at least once — natural for "ask until the input is valid":

Java
int n;
do {
    System.out.print("Enter a positive number: ");
    n = scanner.nextInt();
} while (n <= 0);

The for-each loop (for (String s : list)) works on arrays and anything Iterable. It is the clearest way to visit every element, but it gives you no index, can only go forwards, and you must not add or remove elements of the collection inside it (that throws ConcurrentModificationException; use an explicit Iterator and iterator.remove(), or removeIf). Reassigning the loop variable does not change the array.

Original UniCircle question. Last reviewed 22 Oct 2026.