By Barry A. Burd

If you were stuck on a desert Java island with only one kind of loop, what kind would you want to have? The answer is, you can get along with any kind of loop. The choice between a while loop and a for loop is about the code’s style and efficiency. It’s not about necessity.

Anything that you can do with a for loop, you can do with a while loop as well. Consider, for example, this for loop. Here’s how you can achieve the same effect with a while loop:

int count = 0;

while (count < 10) {

out.print("I've chewed ");

out.print(count);

out.println(" time(s).");

count++;

}

In the while loop, you have explicit statements to declare, initialize, and increment the count variable.

The same kind of trick works in reverse. Anything that you can do with a while loop, you can do with a for loop as well. But turning certain while loops into for loops seems strained and unnatural. Consider this while loop:

while (total < 21) {

card = myRandom.nextInt(10) + 1;

total += card;

System.out.print(card);

System.out.print(" ");

System.out.println(total);

}

Turning this loop into a for loop means wasting most of the stuff inside the for loop’s parentheses:

for ( ; total < 21 ; ) {

card = myRandom.nextInt(10) + 1;

total += card;

System.out.print(card);

System.out.print(" ");

System.out.println(total);

}

The preceding for loop has a condition, but it has no initialization and no update. That’s okay. Without an initialization, nothing special happens when the computer first enters the for loop. And without an update, nothing special happens at the end of each iteration. It’s strange, but it works.

Usually, when you write a for statement, you’re counting how many times to repeat something. But, in truth, you can do just about any kind of repetition with a for statement.