Java- For Each loop
In this article, you will be seeing about the for-each loop in java, how to use a for-each loop with a sample program, and the limitations of the for-each loop.
Loops in Java
Loops are used when a set or a block of code needs to be executed several times. In any programming language, in a set of codes, the code is executed in a sequence i.e. first line of the statement is executed first and followed by each line of the statement.
But, when we need to execute a line or a block of code several times until a certain condition is satisfied, that is where looping takes its role.
Java supports various loops, such as for, while etc.
Let’s take a deeper look on the For each loop in Java
For each loop in Java
The Java for-each loop or enhanced for loop was introduced in Java 5. It provides an alternative approach to traverse the array or collection in Java. For-each loop is mainly used to traverse the array or collection elements.
So, it is recommended to use Java for-each loop for traversing the elements of array and collection because it makes the code readable.
Using for-each loop
‘For each’ is a traversing technique, were this loop optimizes the code, save typing and time.
Here we declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name or the collection name.
Syntax
for(data_type variable : array | collection){ //body of the loop }
The for-each loop consists of data_type with the variable followed by a colon (:), then array or collection.
Sample program using for each to access the elements in an array.
import java.io.*; public class Main { public static void main(String args[]) throws IOException { int ar[] = { 111, 112, 113, 114, 115,}; int a; for (int i : ar) { a = i; System.out.print(a + " "); } } }
Output
111 112 113 114 115
Limitations of For-each loop.
- If you want to modify your array or a collection, the ‘for-each’ loop is not the best choice.
- For- each loop does not work on the basis of the index of the array, so reverse iterating is not possible.
- It can iterate only in the forward direction and in single steps.
- Multiple decision-making statements cannot be applied in the ‘for-each’ loop.

Tag:For-each loop, Java