Search⌘ K
AI Features

The do Statement

Explore the do statement in Java to understand how it guarantees the loop body runs at least once. Learn the syntax and see examples where this loop form is useful, including input validation and displaying sequences.

Syntax

We have seen that the logic of a for loop is identical to the logic of a while loop. Both loops can end immediately after the first test of a given Boolean expression without executing the body of the loop. This behavior is desirable for most loops, so these two statements are the ones that we usually will use for our loops.

Occasionally, however, we will know in advance that the body of a loop must execute at least once. Although we could choose either a while statement or a for statement to implement such a loop, we could also use the do statement. The do statement executes its body, which includes the update step, before evaluating a Boolean expression ...