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:
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.
Hope this helps, keep in touch.
All the Best,
Raf.