For-each Loop in Java
The for-each loop was introduced in Java 5 which is used specifically for traversing a collection in Java. In for-each loop traversal technique, you can directly initialize a variable with the same type as the base type of the array. The variable can be used to access the collection elements without any indexing. It changes to successive elements in the Collection after each iteration.
Introduction to for-each Loop in Java
In Java, there is an interface called as Iterable interface that represents a collection of objects which can be iterated. Arrays, LinkedList, Vector, Stack, etc. are iterables in Java, which means they can be iterated using loops in Java.
The for-each loop in Java, also called as 'enhanced for loop', was introduced in Java 5. It is one of the alternative approaches that is used for traversing arrays.
After accessing the iterable elements, we can perform various operations on them. The main purpose of for-each loop is to traverse the iterable without using the index of iterable elements unlike for loops. The for-each loop makes the code simple as it reduces the code length due to its short and easy syntax.
for-each Loop in Java Syntax
In the above syntax of for-each loop, you can see that we enter four things inside the parentheses after the for keyword.
Those four things are:
- datatype
- variable's name for storing all the iterable elements one by one
- colon symbol followed by
- the iterable name which we want to traverse through.
Note: The for-each loop runs for the whole iterable.
Example:
Output
Explanation:
- In the example given above, we have used a for-each loop to print all the elements of the array arr one by one without even passing the index of the array elements.
- In the first iteration, the first element of the array arr is stored in the variable elem, similarly in the second iteration the value of the variable elem is changed to the next element and so on.
- We have used a print statement in Java to print the array elements. Hence, all the elements of the array arr get printed one after the other.
Flow Diagram of for-each Loop in Java
Let us have a look at the flow of code in for-each loop using the following flow diagram.
Explanation
The above given flow diagram of for-each loop in Java is explained with the help of an example in the steps given below.
Example:
Output
Explanation:
- The for-each loop starts. Input iterable is taken. Here, alpha is our input iterable that is an array.
- Here letter is our iteration variable in which elements of the array get stored.
- The loop runs till the last element of the array i.e. E and then the loop execution ends.
How Does The Java for-each Loop Work?
The working of the for-each loop is very interesting. We create a variable in the for-each loop's round brackets(), that stores each element of the iterable during each iteration.
The code written inside the for-each loop is executed for that particular element which is stored in the for-each loop variable and in the same way, the code is executed for all the elements of the iterable one by one.
It means that the code that is written inside the body of for-each loop runs for all the iterable elements sequentially.
Examples of for-each Loop in Java
Let us see more examples of for-each loop to understand it better.
1. for-each loop to iterate over array elements
Output
Explanation:
- In the above given example, we used for-each loop to iterate through all of the elements of the array called companies.
- In the variable elem, all the elements of the array companies get stored one by one which means that in each iteration the value of the iteration variable changes to the next element of the array.
- Then the code inside the for-each loop's body gets executed for-each of the element.
- Like in the 1st iteration elem = "Amazon", in the 2nd iteration elem = "Microsoft", in the 3rd iteration elem = "Apple" and similarly in the 4th iteration elem = "Meta".
2. for-each loop to iterate over HashMap
The for-each loop can also be used to iterate over a hashmap. Refer to the examples given below.
Output
Explanation:
- In the above example, you can see that we have used for-each loop to iterate over a hashmap in Java.
- In the first for-each loop, we have used keys of the hashmaps for iteration using the .keySet() method which is an iterable that returns keys of the hashmaps. Hence we got all the keys in the output.
- In the second for-each loop, we have used values of the hashmaps for iteration using the .values() method which is an iterable that returns values of the hashmaps. Hence we got all the values in the output.
3. for-each loop for traversing a List of elements
The for-each loop can also be used to traverse a list of elements or items. Refer to the example given below.
Output
Explanation:
- In the above given example, the for-each loop is used for traversing a list called 'myList'.
- As we added three elements(Pen, Pencil and Paper) in the list, when we used for-each loop for traversing through the list, all the three elements were printed in the output.
Advantages of for-each Loop in Java
-
More convenient : When we want to iterate through the whole iterable, for-each loop is an easier and simpler way of doing this as we do not have to provide the index of the elements.
-
It enhances the readability of code : As the syntax of the for-each loop is very simple and short, the code in the for-each loop's body becomes more readable.
-
Decreases the chances of errors : The chances of getting errors also get reduced while using the for-each loop as it is generally less prone to errors.
When Not to Use for-each Loop?
It is also important to know when we can not use a for-each loop?
- Whenever we just want to loop or iterate over a specific portion of the iterable instead of the whole iterable or we want to modify the iterable, we use a for loop instead of the for-each loop.
- Also note that for-each loop can not be executed in a reverse order, unlike for loop which is able to execute the code in the reverse order as well.
- When we need to access the indices of the elements in the iterable, we cannot use for-each loop.
Difference Between For Loop and for-each Loop in Java
For Loop | for-each Loop |
---|---|
The for loop is index based hence the iterable elements are accessed using their indices. | for-each loop is element based hence the iterable elements are accessed directly using the assigned variable. |
For loop was introduced in Java 1. | for-each loop was introduced in Java 5. |
For loop can perform forward as well as backward iteration. | for-each loop can only perform forward iteration. |
Data manipulation of the iterable is possible by using for loop. | Data manipulation of the iterable is not possible by using for-each loop as only the values of the iterable elements are passed, not the reference of iterable elements. |
Conclusion
- for-each loop is also called 'enhanced for loop'.
- for-each loop is an alternative approach for traversing an iterable.
- for-each loop can be used to iterate over iterables such as arrays, hashmaps and lists in Java.
- for-each loop does not require the index of iterable elements.
- for-each loop can not be executed in reverse order.
- for-each loop can not be used to modify the iterable or collection.
- We can use the break keyword in Java to terminate(stop) the for-each loop for some condition.
- for-each loop enhances the code readability and is less prone to errors.