do while loop in java

Let’s learn do while loop in java.

do while loop in java

In do while loop first loop body is executed, then the condition is checked. do while loop will execute loop body at least once, then it depends on the condition whether to execute statements inside loop body or not.

Here condition in do while loop should be of boolean type. Here’s do while syntax.

do{

   body

}while(condition);

Here’s the do while loop syntax we have got the do keyword and right after the keyword we have the left and right curly braces.

After the loop body there’s while keyword and then condition in parentheses and then a semicolon at the end. Semicolon is mandatory in do while.


Flow diagram of do while loop

do while loop in java

Here’s do while java program.

public class DoWhileLoopExample
{
   public static void main(String[] args)
   {
      int a = 5;
      do {
          System.out.print(a);
          a++;
          System.out.print("\n");
      }while(a < 10);
   }
}

Output:

5
6
7
8
9


do while Infinite loop

An infinite do while loop is a loop that will execute endlessly because loop’s expression is always true. Here’s do while infinite loop 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. Let’s see an example on iterating an array using do-while loop.

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

Output:

2
4
6
8


Write a program to display number 1 to 50 using do while loop in java

Let’s learn to write a program to display number 1 to 50 using do while loop in java.

import java.util.Scanner;
public class ProgramDisplayNumber 
{
   public static void main(String[] args) 
   {
      int counter;
      int number;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter maximum number: ");
      number = sc.nextInt();
      counter = 1;
      do{
          System.out.println(counter + " ");
          counter++;
      }while(counter <= number);
      sc.close();
   }
}

Output:

Please enter maximum number: 50
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50


Also read – java overview

Click here to learn difference between while and do while loop in java.