9

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!!");

Domani Tomlindo
  • 239
  • 1
  • 5
  • 12
  • To an extent, it comes down to taste. I would prefer to use a for loop in this situtation, because the declaration is scoped to the loop, and incrementing is outside the loop body. The main difference between the types of loop, however, is that a `do/while` loop executes at least once, whereas a `for` (or a `while`) may not execute. – Andy Turner Oct 09 '18 at 20:42
  • It doesn't matter. BTW, with Java 8+, you can also do `IntStream.rangeClosed(1, 6).forEach(times -> System.out.println("I have printed " + times + " times."));` – David Conrad Oct 09 '18 at 20:45
  • 1
    “And both print the exact same thing” - no they don’t. – JackWhiteIII Oct 10 '18 at 06:11
  • @JackWhiteIII True, I didn't realise that with the `for` loop, it starts with "I have printed 0 times". – Domani Tomlindo Oct 10 '18 at 13:44

6 Answers6

9

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.)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
  • True, I forgot about the fact that, (from personal experiences), nothing executes after the `do-while` loop, and would just have to keep nesting loops. – Domani Tomlindo Oct 09 '18 at 20:53
  • 2
    @DomaniTomlindo sorry, what? once the "while" condition becomes false, the statements which follow it are executed; same goes for the "for" loop – IMil Oct 10 '18 at 03:06
  • @IMil My apologies, (and yes I know this is late), but I was thinking of `do { } while (true);`, which is an infinite loop. I meant that nothing executes after the infinite loop. – Domani Tomlindo Nov 14 '18 at 16:47
4

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.

rzymek
  • 9,064
  • 2
  • 45
  • 59
1

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

David Soroko
  • 8,521
  • 2
  • 39
  • 51
0

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)).
shirish
  • 668
  • 4
  • 9
0

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.

stackFan
  • 1,528
  • 15
  • 22
0

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

neildo
  • 2,206
  • 15
  • 12