The do...while Loop


It is time now to introduce the do...while loop. This kind of loop is not used a lot like the for and while loops but you should know it anyways. A do...while loop is guaranteed to execute one time even if the condition of the while is false. This of the do as the body of the while that will execute at least one time. Check the abstract example below to know how this loop is written.

do{
   code to execute
}
while(condition);


As you can see, the do block will execute before checking the condition. Therefore, that is how we guarantee that it will execute at least once even if the condition if false because the condition checking takes place after the do block.

The code below will show how the do block will work even if the condition is false.

public class Do
{
   public static void main(String args[])
   {
      int condition = 10;

      do{
         System.out.println("I executed!");
      }
      while(condition < 0);
   }
}

Output:

I executed!

As you can see, condition is not less that zero since it has a value of ten. However, the code in the do block executed.

Congratulations

You now know how to use a do...while loop and you understand its concept. This was a fairly simple tutorial because not many concepts are related to the do...while. Move on to the next tutorial.