do-while statement

The do-while statement is like the while statement, except that the associated block always gets executed at least once. Its syntax is as follows:

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

With do-while, you put the statement(s) to be executed after the do keyword. Just like the while statement, you can omit the braces if there is only one statement within them. However, always use braces for the sake of clarity.

For example, here is an example of the do-while statement:

int i = 0;
do {
    System.out.println(i);
    i++;
} while (i < 3);

This prints the following to the console:

0
1
2

The following do-while demonstrates that at least the code in the do block will be executed once even though the initial value of j used to test the expression j < 3 evaluates to false.

int j = 4;
do {
    System.out.println(j);
    j++;
} while (j < 3);

This prints the following on the console.

4