Braces in a do...while Repetition Statement
It isn’t necessary to use braces in the do
...while
repetition statement if there’s only one statement in the body. However, many programmers include the braces, to avoid confusion between the while
and do
...while
statements. For example,
while (condition)
is normally the first line of a while
statement. A do
...while
statement with no braces around a single-statement body appears as:
do statementwhile (condition);
which can be confusing. A reader may misinterpret the last line—while(
condition);
—as a while
statement containing an empty statement (the semicolon by itself). Thus, the do
...while
statement with one body statement is usually written with braces as follows:
do{ statement} while ( ...
Get Java™ How To Program (Early Objects), Tenth 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.