do-while Loop in Java


☞ Following is the syntax of do-while loop.

do{
statement1;
statement2;
………….
}while(condition);

'do' and 'while' is a keyword.

☞Control when reaches ‘do’ keyword, it simply enters into the do-while block. Where it executes statements and then reaches to the end of block. Just after the block while(condition) is encountered. Where condition is evaluated either as true or false. If it is true, control moves back to the keyword ‘do’ and repetition begins. If condition is false, it simply move forward to the next statement of the program.

Example

//Printing 'inspirewebsoft' five times.
public class DoWhileExample {
    public static void main(String[] args) {
        
        int i=1;                //initialization
        do {           
            System.out.println("inspirewebsoft");
            i++;                //flow
        }while(i<=5);           //condition
    
    }
}

Output

inspirewebsoft
inspirewebsoft
inspirewebsoft
inspirewebsoft
inspirewebsoft

Note : Observe the above examples,
1. Loop is executed 5 times in all the mentioned examples.
2. Condition is tested 6 times in while and for loop(i.e. from i=1 to 6), whereas 5 times in do-while loop(i.e. from i=2 to 6).