Do-while loop in java

In this post we are going to learn do-while loop in java.

Do-while loop in java

Java do while loop executes the statements and then evaluates the expression/condition of loop’s body until given condition is true.

So it’s guaranteed to execute the body at least once. Here expression in do while loop should return boolean value. Here’s the syntax,

do
{
   statement(s);
}
while(expression/condition);

How does it work?

do-while loop in java

In the above flow diagram first statements inside loop execute then condition gets evaluated. If condition is true then control gets shifted inside “do” else jumps outside loop.

Also read – continue statement in java

Here’s an example,

public class DoWhileDemo
{
   public static void main(String[] args)
   {
      int x = 1;
      do
      {
         System.out.println(x);
         x++;
      }
      while(x <= 5);
   }
}

Output:

1
2
3
4
5

Infinite loop

An infinite do while loop is a loop that will execute endlessly because loop’s expression is always true. Here’s an example,

public class InfiniteDoWhileDemo 
{
   public static void main(String[] args) throws InterruptedException
   {
      do
      { 
         System.out.println("Start do while");
         System.out.println("End do while");
         Thread.sleep(3 * 1000);
      }while(true);  // press ctrl+c to exit 
   }
}

Similarly we can iterate an array using do while loop,

class DoWhileLoopDemo 
{
   public static void main(String args[])
   {
      int arrNum[] = {2,4,6,8};
      int a = 0;
      do
      {
         System.out.println(arr[a]);
         a++;
      }while(a < 4);
   }
}

Output:

2
4
6
8