Tutorial List
Home
Interview Questions
Interview
Interview Questions
Links
Web Home
About Us

Enhanced for loop in java


We will cover the usage of Enhanced for-loop in this section. This is also referred to as for-each loop. The following code shows how to iterate over the elements in a Collection using the traditional Iterator interface.
ForEachTest.java

package foreach; import java.util.*; public class ForEachTest { public static void main(String[] args) { List numbers = new ArrayList(); numbers.add(1);numbers.add(2);numbers.add(3); Iterator numbersIterator = null; for(numbersIterator = numbers.iterator(); numbersIterator.hasNext();) { System.out.println(numbersIterator.next());; } } }
Though the goal of the above program is traversing over the elements in the list collection, we are depending on the Iterator API to achieve this. A replacement to the Iterator is the usage of Enhanced for-loop, through which it is possible to have a short and a neat code like this,
for(Integer number : numbers)
{
 System.out.println(number);
}
Let us see how the above syntax is used to traverse over the collection. The expression before the symbol ':' is a declaration statement which declares an Integer object called number for holding the individual element from the collection. The expression that follows after the symbol must be a Collection type whose elements can be iterated. Precisely, this type must implement an interface called java.util.Iterable which has a single method called iterator(). During compile-time, the compiler translates the above code which looks very similar to the following,


Iterator intIterator = numbers.iterator(); for(;intIterator.hasNext();) { System.out.println(intIterator.next()); }
Even it is possible to apply this new syntax for type Arrays. So, the following code is perfectly legal and it compiles fine.
int [] numbers = {10, 20, 30, 40, 50};

for(int num : numbers)
{
 System.out.println(num);
}
The enhanced for-loop is just a convenience from the programmer's point of view for iterating over the Collection. But the usage of this loop has some dis-advantages. The first one out of the two is that step-value cannot be incremented. For example, it is not possible to traverse the first element and then the thirth element and so on. And the second dis-advantage is that backward traversal is not possible.