Do while loop java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn do while loop java.

Java do while loop

Java do while loop execute the body even before the test condition. So it’s guaranteed to execute the body at least once.  Here’s the syntax,

Also read – java if else

Syntax :

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

Do While Loop Java

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


do while true

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

Syntax

do
{  
   // code goes here
}while(true);

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 
   }
}


Related Posts