Now that you’ve learned how each loop is defined in Java syntax, how do you know when to use which one? What exactly does each one mean conceptually?
You should use a for loop when you have a pretty good idea of how many iterations will happen. For instance, in the first example, I knew that I wanted to print “Hello World” 10 times. For loops are also very useful when you have a variable that changes in a predictable way, such as incrementing or decrementing by 1. This is demonstrated in the second example.
You should use a while or do-while loop when you aren’t sure how many times something will happen, but you do know what the condition is for the action to keep going. For example, while I haven’t finished reading the book, flip the pages. I might not know how many pages are in the book, but I know that I’ll reach the end eventually and that’s when I’m done. This is demonstrated in the do-while example, since we aren’t sure when the user will be done—we just know that they’ll be done when they enter -1 or the correct number.
For a do-while loop specifically, you should use it when you know for sure that the loop will run at least once. This is why do-while loops are handy for user input.
However, there isn’t really a strict rule for when to use which loop. You can see this from the while loop example, for example. The while loop did the exact same thing as the 2nd for loop example, just in a different way. Often when you are programming, you will find that you can use either a for loop or a while loop. When this is the case, ask yourself which one makes the most sense intuitively and go with it.