Java Reference
In-Depth Information
2.9.3.2 The enhanced for loop
J2SE 5.0 adds a new looping feature called the “enhanced for loop,” also some-
times called the “for/in” loop or the “for each” loop. For compatibility reasons, no
new keyword was added for the enhanced for . Instead a syntax change inside the
parentheses indicates the use of the new loop. Unfortunately, since the enhanced
for loop works on classes and objects or arrays that we don't describe until Chap-
ter 3, we cannot explain the loop's behavior in detail here. Instead, we give a brief
description and defer details until Chapter 10 where we discuss the Iterator
class. Briefly, the new loop appears as follows:
for (type value: container)
statement
The colon is normally read as “in,” thus the name “for/in” loop. The whole
expression can be read “for each value in container, do the statement”. (Of course,
the statement can be a block of statements enclosed in braces.) The “container”
here is a Java object that contains other objects. For example, an array (Section
3.8) is a kind of container. Some arrays can hold object types, others hold primitive
types. If we have an array of int types, we can loop through all elements in the
array as follows:
for (int i: array) statement;
This loops through each element in the array and performs the statement using
each element, one at a time. The real power of the enhanced for loop becomes
evident after we learn about classes and objects (Chapter 3) and, in particular, the
Iterator class (Chapter 10).
2.9.3.3 The while and do-while loops
The while loop goes as follows:
while (test) statement;
It repeatedly executes statement until the test expression returns false .
Here is an example:
while (i < 5) {
i = a.func ();
}
The a.func() method is invoked as long as the variable i is less than 5. The
test is done before the first evaluation of statement ,sothat if the initial test
fails, nothing inside the code block is executed even once. As an alternative, the
do-while statement evaluates the loop code before the test is evaluated. This
ensures that the loop code is executed at least once.
Search WWH ::




Custom Search