do...while Statement
A do...while statement 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:
do
statement
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;
do
{
System.out.print(number + “ “);
number ++;
} while (number <= 20);
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access