Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 405
Domani Tomlindo Avatar asked Oct 09 '18 20:10

Domani Tomlindo


People also ask

Can while loops do counting loops?

We can also do it with a while loop. For example, we could have a computer count up from 1 to 10. We will use a counter variable that we will increment inside the loop. Increment means increase the value by one.

Which is better for loop or while loop in Java?

Use a for loop when you know the loop should execute n times. Use a while loop for reading a file into a variable. Use a while loop when asking for user input. Use a while loop when the increment value is nonstandard.


2 Answers

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

like image 67
Bill the Lizard Avatar answered Oct 16 '22 14:10

Bill the Lizard


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.

like image 24
rzymek Avatar answered Oct 16 '22 13:10

rzymek