Do-while loop in Java is a control flow statement which executes a block of code atleast once and then the condition is checked after each iteration.
Syntax:
do {
// code to be executed repeatedly
} while (condition ) ;
do block : The code within the do block is executed first atleast once without any condition check.
while (condition ) : After the do block executes , the condition which is of type boolean is checked .
- If the condition is true , the loop returns to the do block and executes the code again.
- If the condition is false, the loop terminates and the program continues with the immediate statement after the do-while loop.
Example1 : Print the numbers from 1 to 7 using the do-while loop
class DoWhileExample {
public static void main (String args [] ) {
int count = 1 ;
do {
System.out.println(“Count is : “ + count);
count++;
} while ( count <=7 );
}
}
When to use do-while Loop?
The do-while loop in Java is particularly used in scenarios where you need to ensure that the loop’s body executes atleast once , regardless of the initial state of the condition .
Some uses of do-while Loop are :
- Displaying the login page including signin and password button to enter the user email and password to check if the login info is correct or not.
- Displaying a menu and based on the user choice performing an action where menu should always be presented initially.
If the condition is False initially in do-while Loop:
The do-while loop is different from other loops . It will always execute the block of code at least once , even if the condition is false from start .
Example :
int i=15;
do {
System.out.println(“i is : “ + i);
i++;
} while ( i <7 );
Output :
i is 15
In the above example of do-while loop even though the condition is false, the block of code executed once.
