简体   繁体   中英

Do While Loops Versus For Loops in Java for Counting

When it comes to counting, should a do-while loop be used, or a for loop? Because this:

class Main {
  public static void main(String[] args) {
    int times = 1;
    do {
      System.out.println("I have printed " + times + " times.");
      times++;
    } while (times < 6);
  }
}

Seems to do the exact same thing as this:

class Main {
  public static void main(String[] args) {
    for (int times = 1; times < 6; times++) {
      System.out.println("I have printed " + times + " times.");
    }
  }
}

Is it a difference in speed? Preference? Situation? Personal quirks? Some kind of "Java social taboo"? I have no idea. Either seem to be able to be used for effective counting, just that one takes a lot more. And both print the exact same thing.

System.out.println("Many thanks!!");

You're right, these do the same thing (except one starts counting at 0 and the other at 1, but that's just an implementation detail). If your program knows in advance (before the loop starts) how many times you want the loop to iterate, most Java developers will tell you to go with a for loop. That's what it's designed for.

A while loop or do while loop is better suited for situations where you're looking for a specific value or condition before you exit the loop. (Something like count >= 10 or userInput.equals("N") . Anything that evaluates to a boolean True/False value.)

When faced with these kind of dilemmas, aim for readability and familiarity. You should not concern yourself with micro-optimizations. Focus on readability and clearly conveying you intent. Do as other do in similar situation.

Like @Bill-The-Lizard said, while loop suggests to the reader of your code that you opted for it, because you're not counting, but repeating until a condition is met. At least once - otherwise you'd have chosen while(...){ } loop.

In other words, for , do {} while() and while() { } generally work the same. But one may better convey you intent in your particular piece of logic.

It depends on the programmer's choice when to use for loop or do while loop but the general practice followed by most of the programmers is

  • For loop
    When you know that the loop will execute a predefined number of times(general practice since you can also use for(;true;) which loops forever). For example a loop which runs 10 times or n number of times where n is a variable


for(int i = 0; i < n; i++) {
    //Do something
}
  • While loop
    When you know that the loop should terminate after the evaluation of a specific condition as true or else you want the loop to run forever (like while(true)) and check the break conditions inside the while loop.
    Also the while loop is preferred when you can't figure out the conditions in the first place and start with while(true) but once you write code inside the loop you get good understanding of what's happening and get the idea about which conditions to check thus when to exit the loop. For example


while(x != 0) {
    //Do something;
    x--;
}


while(true) {
    // some code to execute on which the condition depends
    if(condition is true) {
        break;
    }
}
  • Do while loop
    Do while loop is similar to the while loop but with a small difference. That is it allows the first iteration to happen without checking the condition(specified in the while statement, but you can still evaluate the condition inside the block(curly braces)).

I think it's more of a readability and syntactic sugar. This while condition

while (condition)

can also be written as

for (; condition; )

but obviously the first one looks lot better and is more readable.

By convention most Java developers use for loops. Effective Java recommends for loops instead of while loops because the loop variable can use a tighter scope which reduces bugs. http://www.corejavaguru.com/effective-java/items/45

Recent versions of Java also allow the following

    IntStream.range(0, 6).forEach(
            i -> System.out.println("I have printed " + i + " times.")
    );

Beyond personal preferences, this one has the advantage that the index is maintained by the runtime and there is no need for the programmer to ++i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM