Do While Loop

  • Eclipse: Oxygen
  • Java: 1.8

Java allows you to create a do while loop, which likes almost similar to a while loop, is a structure of the repetition control with a termination condition and statements, or block of statement.

Difference between while and do-while loop

In Java While loop, the expression is evaluated at the beginning of the loop and if the expression is evaluated as True then only statements inside the while loop will be executed. So, while loop executes the code block only when the expression is true.

In Java Do While loop, the expression is evaluated at the end of the loop so even if the expression returns false, statements inside the code block will be executed at least once.

Structure

Syntax

Note: Observe the semi-colon at the end of while condition’s parenthesis

For example, take a look at the result of the following statements:

In this statement, the value of i is initialized to 0. Now “do” block prints the value of i then it increments the i by 1, and value will become 1. Then it checks for the condition 1<=2 which is true and prints the value of i equal to 1. It will print repeatedly until condition 11<=10 will become false causing the loop to terminate.

Output:

0

1

2

3

4

5

6

7

8

9

10

In the following example, Java will execute the block first and then check the loop conditional expression. Although the loop exists immediately, and statement block will be executed once and the program output 11.

Output:

11

Note:

  • Use while loop when a loop might not be executed at all.
  • Use do-while loop when the loop is executed at least once.

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu