Card 05/ 09

ConceptDifficulty: Intermediate2 min

Loops in Java: for, Enhanced for, while and do-while

The four forms repeat in the same way and differ in what you know before the loop starts.

A loop repeats a block of code. Java has four loop forms: the counted for, the enhanced for (also called for-each), while, and do/while. They all repeat; what separates them is how much you know before the loop starts.

Printing every item in a basket means visiting each item once. Handling jobs from a queue means carrying on until the queue is empty, however many jobs that turns out to be. Sending a reminder exactly three times means counting. Each of those jobs fits a different form.

The four loop forms and what each one knows in advance
FormYou know in advanceBody may run
for (int i = 0; i < n; i++)How many passes, and the position of eachZero times or more
for (Order o : orders)That you want all of them, and not where they sitZero times or more
while (condition)Nothing: the condition decides before each passZero times or more
do { … } while (condition)That the body must run at least onceOne time or more
java
for (String item : basket) {
    System.out.println(item);
}

while (!queue.isEmpty()) {
    handle(queue.poll());
}

In the enhanced for on the first line, the colon reads as "in": for each item in basket. It has no index (no counter holding the position), so it cannot get the position wrong, and its first line says that you mean to visit every element. That is why it is the form to reach for by default when you have a collection.

while checks its condition before each pass, so its body may never run. do/while checks after the pass, so its body always runs at least once, which suits "ask the user, then decide whether to ask again".

Pick the form by what you know. A counted for used where you do not need the index adds a variable whose only effect is a chance to be one out.