do-while Loop

do-while Loop

A do…..while loop is a special kind of loop that runs the loop at least once even if the base condition is false. This is because the base condition in this loop is checked after executing the block of code. As such, even if the condition is false, the loop is bound to run atleast once. Hence, do…..while loop is also called as an Exit Control Loop.


Syntax:

do {
    //block of code
} while (baseBooleanCondition);

 

Example 1:


public class WhileLoop {
    public static void main(String[] args) {
        int i = 10;
        do {
            System.out.println(i);
            i--;
        } while (i>0);
    }
}


Output:

10
9
8
7
6
5
4
3
2
1

 

Example 2:


public class WhileLoop {
    public static void main(String[] args) {
        int i = 10;
        do {
            System.out.println(i);
            i--;
        } while (i>10);
    }
}


Output:

10

As we can see, even if condition is false, the loop runs at least once.