Enhanced
|
| INTERMEDIATE |
The usual way to step through all the elements of an array
in order is with a "standard" for
loop, for example,
for (int i = 0; i < myArray.length; i++) { System.out.println(myArray[i]); }
The so-called enhanced for loop is a simpler way to do this same thing. (The colon in the syntax can be read as "in.")
for (int myValue : myArray) { System.out.println(myValue); }
The enhanced for loop was introduced in Java 5 as a simpler way
to iterate through all the elements of a Collection (Collections are not covered
in these pages). It can also be used for arrays, as in the above example, but
this is not the original purpose.
Enhanced for loops are simple but inflexible. They can be used
when you wish to step through the elements of the array in first-to-last order,
and you do not need to know the index of the current element. In all other cases,
the "standard" for loop should be
preferred.
Two additional statement types, break
and continue, can also control the
behavior of enhanced for loops.
| ADVANCED |
The break and continue statements can be used with statement labels.