Card 05/ 09
All 9 cards
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.
| Form | You know in advance | Body may run |
|---|---|---|
for (int i = 0; i < n; i++) | How many passes, and the index of each | Zero times or more |
for (Order o : orders) | That you want all of them, and not where they sit | Zero times or more |
while (condition) | Nothing — the condition decides each time | Zero times or more |
do { … } while (condition) | That the body must run at least once | One time or more |
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.