Java Reference
In-Depth Information
Example 3.9
A Java
while
statement
while (greble != null)
{
greble.glib();
greble = treempl.morph();
}
Technically, the
while
statement consists of the expression and a single
statement, but that single statement can be replaced by a set of statements en-
closed in braces (you know, the characters
{
and
}
). We will always use braces,
even if there is only one statement in our
while
loop. Experience has shown
that it's a safer practice that leads to code that is easier to maintain. Just treat
it as if the braces were required syntax, and you'll never forget to add them
when you add a second statement to a loop.
The
do-while
loop.
To put the terminating check at the bottom of the
loop, use
do-while
as shown in Example 3.10. Notice the need for the
terminating semicolon after the expression.
Example 3.10
A Java
do-while
statement
do {
greble.morph();
xrof = treempl.glib();
} while (xrof == null);
Die-hard Pascal programmers should note that Java has no
repeat-until
statement. Sorry. Of course the logic of an
until(condition)
is equivalent
to
do-while(!condition)
.
The
for
loop.
The
for
loop in Java is very similar to C/C++. It consists of
three parts (Example 3.11):
• The initializing expression, done up front before the loop begins
• The conditional expression for terminating the loop