How to use Enhanced FOR loops in Java

Hello everyone!

After today’s course connect at Sheridan College, I thought about writing this little piece on how we use the ENHANCED FOR LOOP in Java.

The feature was introduced in the Java SE 5 platform and makes it somewhat easier to iterate across Arrays and Java collections such as ArrayLists (or dynamic arrays). It is simple:

Screen Shot 2015-05-28 at 8.53.16 PM

In the enhanced loop, instead of declaring a variable to hold the index of the element and increase the index (using i++), you declare a variable to hold the element itself, so it must always be of the same type of the objects held in the array (or collection). There is no need to define when the loop is going to end, java goes all the way until the last element of the collection.

The colon in the syntax can be read as “in“, such as “for the dog in turn in the dogs array, do something”.

Lets see again how it works with the Java collection ArrayList.

Screen Shot 2015-05-28 at 9.13.07 PM

Hope this helps, keep in touch.

All the Best,


%d bloggers like this: