Card 05/ 09

ConceptDifficulty: Intermediate1 min

The Four Shapes of a Java Loop

You need to do the same thing to every order in a list, or until a queue is empty, or exactly ten times. Java has four loop forms, and what separates them is how much you know before the loop starts.

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 index 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 each timeZero 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());
}

The enhanced form on the first line — the one with the colon — is the one to reach for by default. It has no index, so it cannot have an index bug, and it says in its first line that you intend to visit everything.

Pick the form by what you actually know. Reaching for a counted for when you do not need the index is how a loop acquires a variable that exists only to go wrong.