5.4. The enhanced for loop

[5.2] Create and use for loops including the enhanced for loop

The enhanced for loop is also called the for-each loop, and it offers some advantages over the regular for loop. It also has some limitations.

5.4.1. Iteration with enhanced for loop

To start with, the regular for loop is cumbersome to use when it comes to iterating through a collection or an array. You need to create a looping variable and specify the start and end positions of the collection or the array, even if you want to iterate through the complete collection or list. The enhanced for loop makes the previously mentioned routine task quite a breeze, as the following example demonstrates for the ArrayList myList:

ArrayList<String> ...

Get OCA Java SE 8 Programmer I Certification Guide now with O’Reilly online learning.

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