1
0

Do While Loop in Java

The third looping statement in Java is the do-while statement. In this statement, the while expression is evaluated at the end of the loop. So the statements in the body of the loop are executed first and then the condition is evaluated. If the condition is true the body of the loop is executed again otherwise the loop is terminated. The syntax of the do-while statement is as follows:

do
{
    statement(s);
} while (expression);

The difference between do-while and while is that do-while evaluates its expression at the end of the loop instead of the top. Therefore, the statements within the do block are always executed at least once even if the expression is false, as shown in the following DoWhileDemo program:

Program to print numbers from 1 to 0 using a do-while loop:

class DoWhileLoop
{
    public static void main(String[] args)
    {
        int count = 1;
        do
        {
            System.out.println("Count is: " + count);
            count++;
        }while(count <= 11);
    }
}

This loop is very useful when the value of the condition variable is determined by some statement inside the body of the loop. For example, if the execution of a program is controlled by the user’s response.

Leave a Reply