Pages

Saturday, July 12, 2014

Enhanced for each loop in Java

For-each loop in Java

The for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. The enhanced for loop is also called the for-each loop, and it offers some advantages over the regular for loop. It also has some limitations.

To start with, the regular for loop is cumbersome to use when it comes to iterating through a collection or an array. You need to create a looping variable and specify the start and end positions of the collection or the array, even if you want to iterate through the complete collection or list. The enhanced for loop makes the previously mentioned routine task quite a breeze, as the following example demonstrates for an ArrayList myList:

You can read the colon (:) in a for-each loop as “in”.The for-each loop is a breeze to implement: there’s no code clutter, and the code is easy to write and comprehend. In the previous example, the for-each loop is read as “for each element val in collection myList, print the value of val.”You can also easily iterate through nested collections using the enhanced for loop. In this example, assume that an ArrayList of exams, levels, and grades are defined as follows:

The output of this code is as follows:JavaOracleBasicAdvancedPassFail

The nestedArrayList can be compared to a multidimensional array

For-each with arraysThe enhanced for loop is again a breeze to use to iterate through nested or non-nested arrays. For example, you can use the following code to iterate through an array of elements and calculate its total:

Modification within for-each loopWhat happens when you try to modify the value of the loop variable in an enhanced for loop? The result depends on whether you’re iterating through a collection of primitive values or objects. If you’re iterating through an array of primitive values, manipulation of the loop variable will never change the value of the array being iterated because the primitive values are passed by value to the loop variable in an enhanced for loop.When you iterate through a collection of objects, the value of the collection is passed by reference to the loop variable. Therefore, if the value of the loop variable is manipulated by executing methods on it, the modified value will be reflected in the collection of objects being iterated:

Sample Output:JavaLattteJavaOracleLattteOracleLet’s modify the previous code. Instead of calling the method append on the loop variable val, let’s assign to it another StringBuilder object. In this case, the original elements of the array being iterated will not be affected and will remain the same:

Sample Output:JavaLattteJavaLattte

Limitations of the enhanced for loopThough a for-each loop is a good choice for iterating through collections and arrays, it can’t be used in some places.CAN’T BE USED TO INITIALIZE AN ARRAY AND MODIFY ITS ELEMENTSCan you use an enhanced for loop in place of the regular for loop in the following code?

The simple answer is “no.” Although you can define a “counter” outside of the enhanced for loop and use it to initialize and modify the array elements, this approach defeats the purpose of the for-each loop. The existing for loop is easier to use in this case.CAN’T BE USED TO DELETE OR REMOVE THE ELEMENTS OF A COLLECTIONBecause the for loop hides the iterator used to iterate through the elements of a collection, you can’t use it to remove or delete the existing collection values because you can’t call the remove method.If you assign a null value to the loop variable, it won’t remove the element from a collectionCAN’T BE USED TO ITERATE OVER MULTIPLE COLLECTIONS OR ARRAYS IN THE SAME LOOPThough it’s perfectly fine for you to iterate through nested collections or arrays using a for loop, you can’t iterate over multiple collections or arrays in the same for-each loop because the for-each loop allows for the creation of only one looping variable. Unlike the regular for loop, you can’t define multiple looping variables in a for-each loop.Use the for-each loop to iterate arrays and collections. Don’t use it to initialize, modify, or filter them.Advantages enhanced for loop