Powered by Blogger.

Understanding foreach loop in Java

>> Sunday, January 8, 2012

To make iteration over arrays and other collections more convenient Java5 extended the basic for loop and it is named as for-each Loop and also called as enhanced for loop or foreach loop.

The for-each loop is used to access each successive value in a collection of values.

This foreach loop is commonly used to iterate over an array or a Collections class (eg, ArrayList).

For-Each loop Syntax is given below

//... Foreach loop over all elements in arr.
for (type var : arr) {
Actual working mechanism using indexes in Java4 and equivalent to for loop.
//... For loop using index.
for (int i = 0; i < arr.length; i++) {
    type var = arr[i];
In Collections we can use variable as an Object to iterate all elements in the object. Here we can work more progressively with collections. No need to use Iterator.
//... Foreach loop over all elements in arr.
for (type var : coll) {
Using iterator we can iterate the elements with specified methods and equivalent to for loop.
//... Loop using explicit iterator.
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
Advantages of for-each Loop:
  • Less error prone code
  • Improved readability
  • Less number of variables to clean up
  • Cannot be used where the collection is to be altered while traversing/looping through
  • My not be suitable while looping through multiple collections in parallel
  • Example program on for-each loop.

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.