Beginning Programming with Java For Dummies
Book image
Explore Book Buy On Amazon
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:

<strong>int count = 0;</strong>

while (<strong>count < 10</strong>) {

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

out.print(count);

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

<strong> count++;</strong>

}

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.

About This Article

This article is from the book:

About the book author:

Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.

This article can be found in the category: