do-while Loops

The do-while loop is similar to the while loop, but the conditional test goes in a different place. The following is an example of a do-while loop:

do {    // the statements inside the loop go here} while (gameLives > 0);

Like the while loop, this loop continues looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop, instead of before them.

When the do loop is reached for the first time as a program runs, the statements between the do and while are handled automatically, and then the while condition is tested to determine whether the loop should be repeated. If the while condition is true, the loop goes around ...

Get Sams Teach Yourself Java™ in 24 Hours, Sixth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.