Sometimes it is necessary that the block or statement must be executed at least once but if the condition is initially at a false state then the block will not be executed.
So for the situation where a block of code must be executed at least once, a do-while loop comes in play.
do–while is an exit-control loop that is it checks the condition after the first execution of the block. And it keeps executing the block until the condition state is false.
Flowchart for do-While loop in Java:
Syntax of do..while loop:
1 2 3 4 | do { statements.. }while (condition); |
Example of a do-while loop in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class dowhileloopTest { public static void main(String args[]) { int a = 1; do { //will be executed once System.out.println("Value of x:" + a); a++; } while (a < 5); } } |
Output:
1 2 3 4 | Value of x:1 Value of x:2 Value of x:3 Value of x:4 |