Java Enhanced For Loop (For-each Loop)
JAVA ENHANCED FOR LOOP
The enhanced for loop is also called the for-each loop and has some advantages over the regular for loop. A for-each loop is designed to cycle through a collection of objects, sequentially from start to finish.
The general form of the for-each version of the for loop is like
for(type count_var : collection) statement-block
The type specifies the type of the variable count_var. It receives the elements from a collection one at a time and iterates from beginning to end. With each iteration of the loop, the next element in the collection is retrieved and stored in count_var. The loop repeats until all elements in the collection have been obtained. Because the iteration variable receives values from the collection, the type must be the same as(or compatible with) the elements stored in the collection. Thus, when iterating over arrays, type must be compatible with the element type of the array.
We can also easily iterate through nested collections using the enhanced for loop.
Example:
import java.util.ArrayList; public class Myclass { public static void main(String[] args) { ArrayList<String> myList = new ArrayList<String>(); myList.add("Java"); myList.add("Loop"); myList.add("for-each"); for (String val : myList) { System.out.println(val); } } }
Output:
Java Loop for-each
One thing we should consider here is, what will happen if we try to modify the loop variable in enhanced for loop?.
The answer lies in the fact that, if we are traversing through the object or primitive type. If we’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 we 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.
Limitation of enhanced for loop
- It can’t be used to delete or remove the elements from a collection:- The enhanced for loop hides the iterator used to iterate through the elements of a collection, we can’t use it to remove or delete the existing collection values because we can’t call the remove method.
- We can not iterate over multiple collection arrays in the same loop.
- The enhanced for loop can’t be used to initialize an array and modify its elements.