Do While Loops Versus For Loops in Java for Counting
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.