Java: do…while loop

do {
    tryConnect();
} while (!isConnected());

In a dowhile loop the loop body is executed once before the condition is checked.

do { instructions } while (condition); true false // ...

This loop construct is far less common than ordinary while loops and for loops.

Equivalent while loop

The while loop below is equivalent to the dowhile loop at the top of this article:

tryConnect();
while (!isConnected()) {
    tryConnect();
}

Note: In a dowhile loop, the while (…) part must be followed by a ;.

Adding a ; in an ordinary while loop is however a grave mistake. See Beware of accidental semicolons in while and for loops!

Optional Braces

For single statement bodies, the braces are optional, just as with if statements and other loop constructs.

Example: These two snippets are equivalent:

do {
    guess();
} while (!correctAnswer());
do
    guess();
while (!correctAnswer());

Comments

Be the first to comment!