Java - Do While Loop

Java

Share

In this tutorial we will learn about do while loop in Java programming language.

A do while loop is similar to a while loop that we discussed in the previous tutorial. Feel free to check that out.

do-while syntax

do {
  // body of the loop
} while (condition);

Where, condition is some condition that needs to be satisfied to execute the code inside the body of the loop.

Example #1: Write a program in Java to print "Hello World" five times using do while loop

For this we will use an integer counter variable, initially set to 1.

For the condition we will use counter <= 5.

class LoopExample {
  public static void main(String args[]) {
    int counter = 1;
    do {
      System.out.println("Hello World");
      counter++;
    } while( counter <= 5 );
  }
}

Output:

Hello World
Hello World
Hello World
Hello World
Hello World

In the body of the loop we are printing the string "Hello World" using the println() method.

We are also incrementing the counter variable value by 1 using the ++ increment operator.

Example #2: Write a program in Java to print from 1 to 10 but quit if multiple of 7 is encountered

class LoopExample {
  public static void main(String args[]) {
    int counter = 1;
    do {
      System.out.println(counter);
    
      if (counter % 7 == 0) {
        System.out.println("Multiple of 7 encountered. Quitting loop!");
        break;
      }

      counter++;
    } while( counter <= 10 );
  }
}

Output:

1
2
3
4
5
6
7
Multiple of 7 encountered. Quitting loop!

So, inside the body of the loop we have an if statement to check if counter is a multiple of 7 or not.

If a number N gives 0 as remainder when divided by 7 then it is a multiple of 7. And to check multiple we are using the Modulus Operator %.

Difference between while and do-while loop

In while loop we first check the condition and if it is satisfied then we execute the body of the loop. So, it is an entry controlled loop.

In do-while loop we first execute the body of the loop then we check the condition. So, it is an exit controllde loop.

The while loop will execute 0 or N times depending on whether the condition is not satisfied or satisfied.

The do-while loop will execute at least once even if the condition is not satisfied.

Share

Recently Updated