Java Reference
In-Depth Information
for the switch expression. And finally, it is not legal to have two or more case labels
with the same value or more than one default label.
The while Statement
The while statement is a basic statement that allows Java to perform repetitive
actions—or, to put it another way, it is one of Java's primary looping constructs . It has
the following syntax:
while ( expression )
statement
The while statement works by first evaluating the expression , which must result in
a boolean or Boolean value. If the value is false , the interpreter skips the state
ment associated with the loop and moves to the next statement in the program. If it
is true , however, the statement that forms the body of the loop is executed, and the
expression is reevaluated. Again, if the value of expression is false , the inter‐
preter moves on to the next statement in the program; otherwise, it executes the
statement again. This cycle continues while the expression remains true (i.e.,
until it evaluates to false ), at which point the while statement ends, and the inter‐
preter moves on to the next statement. You can create an infinite loop with the syn‐
tax while(true) .
Here is an example while loop that prints the numbers 0 to 9:
int count = 0 ;
while ( count < 10 ) {
System . out . println ( count );
count ++;
}
As you can see, the variable count starts off at 0 in this example and is incremented
each time the body of the loop runs. Once the loop has executed 10 times, the
expression becomes false (i.e., count is no longer less than 10), the while state‐
ment finishes, and the Java interpreter can move to the next statement in the pro‐
gram. Most loops have a counter variable like count . The variable names i , j , and k
are commonly used as loop counters, although you should use more descriptive
names if it makes your code easier to understand.
The do Statement
A do loop is much like a while loop, except that the loop expression is tested at the
bottom of the loop rather than at the top. This means that the body of the loop is
always executed at least once. The syntax is:
do
statement
while ( expression );
Notice a couple of differences between the do loop and the more ordinary while
loop. First, the do loop requires both the do keyword to mark the beginning of the
Search WWH ::




Custom Search