Use a while Loop to Repeat Based on a Condition

You use a for loop when you need to run a piece of code a fixed number of times. But what if you aren’t certain just how many times you need to loop? What if you wanted to loop as long as needed, as long as some other condition is still true? In that case, you’d use a while loop. A while loop will keep executing a piece of code as long as the Boolean condition is true:

 
while​ (stillHungry) {
 
// ...
 
// Something better set stillHungry to false!
 
}

In a way, it’s kind of a mix between an if statement and a for loop: it loops over code the same way a for loop does, but it keeps looping as long as the condition is true, testing the condition like an if does.

And yes, if you forget to ...

Get Learn to Program with Minecraft Plugins, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.