Do While Loops Versus For Loops in Java for Counting

  • A+
Category:Languages

Ok so this is a question that has probably been asked a thousand times, but none of them that I found really had an answer that I was particularly looking for. I have done much research on this topic but to no avail. My question is: 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 = 0; 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.

Sorry if this question isn't written very well, this is the first question I have asked on this site.

Thanks!!

 


You're right, these do exactly the same thing. If you know in advance (before the loop starts) how many times you want it 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: