Java Reference
In-Depth Information
for (int i = 0; i < 10; i++)
System.out.println(i);
is equivalent to
int i = 0;
while (i < 10)
{
System.out.println(i);
i++;
}
Do-While Statement
The do-while statement repeatedly executes a statement while its Boolean expression
evaluatestotrue.Unlikethewhilestatement,whichevaluatestheBooleanexpressionat
thetopoftheloop,do-whileevaluatestheBooleanexpressionatthebottomoftheloop.
This statement has the following syntax:
do
statement
while(
Boolean expression
);
Do-whileconsistsofthe
do
reservedword,followedbya
statement
torepeatedly
execute,followedbythe
while
reservedword,followedbyaparenthesized
Boolean
expression
header, followed by a semicolon.
The do-while statement first executes the other
statement
. It then evaluates the
Boolean expression
.Ifitistrue,do-whileexecutestheother
statement
.Once
again,the
Boolean expression
isevaluated.Ifitisstilltrue,do-whilere-executes
the
statement
. This cyclic pattern continues.
Thefollowingexampledemonstratesdo-whilepromptingtheusertoenteraspecific
uppercase letter or its lowercase equivalent:
int ch;
do
{
System.out.println("Press C or c to continue.");
ch = System.in.read();
}
while (ch != 'C' && ch != 'c');