Do While Loop Java

Hey guys!! Welcome to flower brackets blog. In this post we are going to learn do while loop in 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);

Flow diagram

Do While Loop Java

do while loop 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 do..while loop in java

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

Syntax

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

Example

public class InfiniteDoWhileDemo 
{
   public static void main(String[] args) 
   {
      do
      { 
         System.out.println("infinitive do while demo"); 
      }while(true);  // press ctrl+c to exit 
   }
}

Output

infinitive do while demo
infinitive do while demo


Conclusion

That’s it guys. This is all about do-while loop in java with example. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you you haven’t already.

Do share this post if you like.

Related Posts