Java Reference
In-Depth Information
An enhanced
for
statement has the following properties:
The data type of the iterator must be compatible with the data type of the collection.
The scope of the iterator is the body of the loop.
The number of iterations of the loop equals the size of the collection. If the collection is
empty, the body of the loop does not execute.
The collection must be an array or an object of type
java.lang.Iterable
, an interface
introduced in Java 5.0 exclusively for
for-each
loops.
Let's start with a simple example to demonstrate how it looks. Examine the following
enhanced
for
statement and try to determine its output:
3. char [] grades = {'A', 'B', 'C', 'D', 'F'};
4. for(char grade : grades) {
5. System.out.print(grade + “ “);
6. }
The collection in this example has fi ve elements, so the loop executes fi ve times. The
grade
iterator is initially
'A'
, then
'B'
, and so on. The output is
A B C D F
You must declare the iterator within the enhanced
for
statement; it cannot be a variable
that is already declared. For example, the following code does not compile:
9. char grade;
10. for(grade : grades) { //does not compile!
11. System.out.print(grade + “ “);
12. }
The compiler complains that
grade
on line 10 is not a statement and that a semicolon is
expected. The compiler thinks I am trying to declare a basic
for
loop on line 10 because
the declaration of the iterator does not include a data type.
The Scope of Enhanced
for
Loop Variables
The scope of the iterator in an enhanced
for
loop is only within the body of the loop.
To demonstrate, study the following code and see if you can determine its result:
15. String [] replies = {“Hello”, “Hi”, “How are you?”};
16. String s = “Bye”;
17. for(String reply : replies) {
18. s = reply;
19. }
20. System.out.println(s);
21. System.out.println(reply);
Search WWH ::
Custom Search