E.6. Enhanced for Statement

The enhanced for statement iterates through the elements of an array without using a counter, thus avoiding the possibility of “stepping outside” the array. We show how to use the enhanced for statement with the Java API’s prebuilt data structures (called collections) in Section E.12. The syntax of an enhanced for statement is:

for ( parameter : arrayName )   statement

where parameter has a type and an identifier (e.g., int number), and arrayName is the array through which to iterate. The type of the parameter must be consistent with the type of the elements in the array. As the next example illustrates, the identifier represents successive element values in the array on successive iterations of the loop.

Figure ...

Get Android™ How to Program, Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.