Saturday, September 19, 2009

The Enhanced For Loop in Java

The enhanced for loop is one of the easiest to understand language changes in Java. It allows us to iterate through a collection or an array without having to create an iterator or having to check for the beginning and end conditions for a counter variable. Overall what this means is that with this enhanced for loop we can write more cleaner, more readable and error free code.

It is not a very complex thing to understand , so let me start with some example code. Suppose we have an array of String named guestList, which contains the names of people who are invited in a party, and we need to check whether John Doe is invited in the party or not. Here is the code which we may write using the old for loop :

/* leaving the customary details of class and method declarations , writing only the code necessary to explain the topic. */

for(i=0; i<guestlist.length; i++){
if(guestList[i].equals("John Doe")){
System.out.println("John Doe is amongst the invited guests");
return;
}
}
//code to print that John Doe is not invited

This was the usual way we would have written our code earlier, but now lets see how the enhanced for loop would reduce the clutter and complexity from the code.

/*the enhanced for loop version */
for(String str: guestList){

if(str.equals("John Doe"){
System.out.println("John Doe is amongst the invited guests");
return;
}
}
//code to print that John Doe is not invited.


Do you see how simpler our code has become this, of course the meaning of this might not be clear to you right now, i will explain it to you just now. This enhanced for loop is also called the For Each Loop, the reason lies in its interpretation. For example the Ist line of the code

for(String str: guestList)

can be interpreted as
" for each String str in guestList"
Here the variable str points to the currently selected object in the collection and all operations inside the body of the for loop will be performed on this object. With each iteration of the loop, str points to the next object in the collection, until all the items in the collection are exhausted (or we explicitly break from the loop). As you might have noticed we do not need need to determine how many elements are in the array before looping. There is also no need to specify how to increment the current position, the compiler takes care of it. This also takes two sources of error out of the equation, we do not need to maintain any counter variable and check for boundary conditions.

Rest of the lines of the code must be self explanatory to you, as str points to the currently selected String object in the array, we can directly perform the comparison using the equals method and do rest of the stuff.

The Enhanced For Loop comes to the benefit to even more greater extent when we need to loop through a collection (specially generics). Different type of collection provides different methods to loop through them, for example to iterate through an Iterator one would use the hasNext() method, while to loop through an ArrayList one would check for the end of the list with the help of size() method and retrieve objects using the get method of the ArrayList implementation. What I want to say is that earlier we needed to remember different methods for different type of collections, but those days are over now with the advent of the enhanced for loop.

Consider the following code in which we have to loop through a generic Iterator, let us say that this Iterator will also contain the list of names of guests invited to our party

/*guestList is the name of the Iterator which contains Strings*/

while(guestList.hasNext()){
String guest= guestList.next();
if(guest.equals("John Doe")){
System.out.println("John Doe is invited");
return;
}
}


This was how we used to loop through an iterator earlier, there would have been a different method used with some other data structure. But lets see the same example written with enhanced for loop:

for(String name: guestList){
if(name.equals("John Doe"){
System.out.println("John Doe is invited");
return;
}
}


See the simplicity of code now? We can use the above code with "almost" any type of collection, in a way it also makes our code independent of the kind of data structure used to store the data. guestList could have been an ArrayList, a LinkedList, a Set , etc. and the above code wouldn't need to change for that.

Limitations of Enhanced For Loop:

Ok!!! Enhanced for loops have their utilities in a variety of situations, but they by no means make the old "classical for loop" obsolete. I will finish this post with the following short list which tells you the things which you can not do with the enhanced for loop :
  • remove elements as you traverse collections
  • modify the current slot in an array or list
  • iterate over multiple collections or arrays
Hopefully i made the concept of enhanced for loop clear with this post, any questions or positive criticisms are welcome through comments.

4 comments:

  1. but i think, java m forEach loop use nhi hota......

    ReplyDelete
  2. It's been in Java since version 5.

    ReplyDelete
  3. Very detailed explanation sir! Not anything else on the web like it :)

    ReplyDelete