How to Use a do…while Statement in Java

By Doug Lowe

A do…while statement in Java programming is similar to a while statement but with a critical difference: In a do…while statement, the condition that stops the loop isn’t tested until after the statements in the loop have executed. The basic form of a do…while statement is this:

while (expression);

The while keyword and the expression aren’t coded until after the body of the loop. As with a while statement, the body for a do…while statement can be a single statement or a block of statements enclosed in braces.

Also, notice that a semicolon follows the expression. do…while is the only looping statement that ends with a semicolon.

Here’s a loop that counts from 1 to 20:

int number = 1;
    System.out.print(number + " ");
    number ++;
} while (number <= 20);

The statement or statements in the body of a do…while statement always execute at least one time. By contrast, the statement or statements in the body of a while statement aren’t executed at all if the while expression is false the first time it’s evaluated.

You can exit out of the middle of a loop by using a break statement. You can also use a continue statement to skip an execution of the loop.