Java gives you three loop forms and they differ in one decisive way. The for loop is for a known number of passes. The while loop is for a condition that you check before the body runs. And the do-while loop is for a condition that you check after the body, which means that the body always runs at least once. You pick the right one and most of the loop bugs disappear.
The previous lesson in this module covered "How Does switch Work, Including the Modern Arrow Form?", and the next lesson in this module is about "When Do break and continue Matter in Loop Control?".
When should you reach for a for loop?
The for loop bundles three things into one line. There is an initialiser that runs once, there is a condition that is tested before every pass, and there is an update that is applied after every pass. The initialiser, the condition and the update are the state of the loop, and keeping them together on one line is what makes the behaviour of the loop obvious when you read it later.
public class BasketTotal {
public static void main(String[] args) {
double[] prices = {4.50, 2.99, 12.00, 1.25};
double total = 0;
for (int i = 0; i < prices.length; i++) {
total += prices[i];
}
System.out.println("Items: " + prices.length);
System.out.printf("Total: %.2f%n", total);
}
}The output is this.
Items: 4
Total: 20.74And using the index matters whenever you need the position as well as the value, for instance when you want to print a numbering or when you look up a parallel array. If you only need the values then the enhanced for loop removes the index bookkeeping entirely.
What does the enhanced for loop save you?
The enhanced for loop, sometimes called the for-each loop, walks an array or a collection and it hands you each element without giving you the index. It needs no initialiser, no bound check and no increment, so there is nothing in it to get wrong.
public class BasketForEach {
public static void main(String[] args) {
double[] prices = {4.50, 2.99, 12.00, 1.25};
double total = 0;
for (double price : prices) {
total += price;
}
System.out.printf("Total: %.2f%n", total);
}
}It is the same 20.74 total, with three fewer moving parts. The trade is that you cannot modify the array while you are iterating it with the enhanced form, because changing the structure underneath the loop confuses the iterator. If you need to remove the elements then you use an index-based loop.
How does a while loop differ?
A while loop has only a condition. It tests that condition first and it runs the body only if the condition is true, and then it goes back and tests again. The loop ends when the condition turns false, which means that something inside the body has to change the condition or the loop never ends.
public class Countdown {
public static void main(String[] args) {
int seconds = 5;
while (seconds > 0) {
System.out.println("Launch in " + seconds + "s");
seconds--;
}
System.out.println("Liftoff");
}
}The output counts down from five and it ends with the liftoff line. The same three numbers can come out of all three of the loop forms, and the difference is only in where the state lives.
public class LoopForms {
public static void main(String[] args) {
System.out.print("for: ");
for (int i = 1; i <= 3; i++) {
System.out.print(i + " ");
}
System.out.println();
System.out.print("while: ");
int j = 1;
while (j <= 3) {
System.out.print(j + " ");
j++;
}
System.out.println();
System.out.print("do-while: ");
int k = 1;
do {
System.out.print(k + " ");
k++;
} while (k <= 3);
System.out.println();
}
}All three of them print the same thing, but the for loop keeps the counter inside its own header while the other two need a variable declared beforehand. That extra declaration is the practical cost of a while loop, and it is the reason that a while loop suits the case where the number of the passes is genuinely unknown.
When is do-while the right choice?
A do-while loop runs the body first and it tests the condition afterwards, so the body executes at least once even when the condition is false from the start. That makes it the right shape for anything where the first attempt must happen before you can ask whether to try again. Entering a menu, reading one value and validating a single record are the usual examples.
public class DoWhileRuns {
public static void main(String[] args) {
int queueSize = 0;
System.out.println("-- while --");
while (queueSize > 0) {
System.out.println("processing a job");
queueSize--;
}
System.out.println("-- do-while --");
do {
System.out.println("processing a job");
queueSize--;
} while (queueSize > 0);
System.out.println("done");
}
}The output makes the difference obvious.
-- while --
-- do-while --
processing a job
doneThe while loop printed nothing at all, because the condition was false before the first test. The do-while loop printed its message once even though the queue was empty, because the body had to run before the condition was ever consulted. If your program must never run the body when the condition starts out as false then you use a plain while loop.
What are the off-by-one traps to avoid?
Most of the loop bugs are one iteration out. The classic version compares the counter with the less-than-or-equal instead of the less-than, and that walks one element past the end of the array.
public class OffByOne {
public static void main(String[] args) {
String[] names = {"Ada", "Grace"};
for (int i = 0; i <= names.length; i++) {
System.out.println(i + " -> " + names[i]);
}
}
}The first two elements print normally and then the program fails.
0 -> Ada
1 -> Grace
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2The arrays in Java are zero-based, so the last valid index is the length minus one, and the correct test is i < names.length. The same off-by-one shows up in the countdown loops, where the greater-than-or-equal to zero gives you the zero as well.
Cheat sheet
the form the condition tested the minimum passes reach for it when
---------------------- -------------------- ------------------ --------------------------
for before each pass zero you know how many times
for (T x : items) before each pass zero you need the values and
not the positions
while before each pass zero the number of passes is
decided at run time
do-while after each pass one the body has to run before
you can decide to stop
Try it yourself: write a program that reads a series of the prices from a fixed array and it prints the running total after each item, using a for loop first and then the enhanced for loop, and confirm that both produce the same lines. Next, change the enhanced loop into a do-while loop that runs at least once and watch what happens with an empty array. Finally, write a loop that counts down from 10 to 1 and deliberately use the greater-than-or-equal to zero instead of the greater-than zero, then fix it and explain the difference in one sentence.