The for-each loop in Java is a powerful looping construct that allows you to iterate through each item in an array or a collection more clearly. This construct was introduced in Java SE 5.0 and is also known as enhanced for loop in Java.
The for-each loop provides a simple and concise way to traverse elements of arrays and collections without the complexity of the traditional for loop. It automatically retrieves each element without requiring index handling.
You can use this loop when you want to access every element but do not need to modify or track the index.

Syntax of For-Each Loop in Java
The basic syntax of for-each loop or enhanced for loop is very simple and straightforward.
for (DataType variable : collection) {
// code to execute for each element.
}In the above syntax of the enhanced for loop:
- DataType represents the type of elements in the array or collection.
- variable temporarily stores each element during iteration.
- collection represents the array or collection over which the loop iterates.
Basic Examples of For-Each Loop
Let’s take some examples based on for-each loop in Java programming.
Example 1: For-Each Loop with Array
package javaPrograms;
public class ForEachArrayEx {
public static void main(String[] args) {
// Create an array of elements of type int.
int[] numbers = {10, 20, 30, 40};
// Iterating over each element.
for (int num : numbers) {
System.out.println(num);
}
}
}Output:
10
20
30
40Example 2: For-Each Loop with String Array
package javaPrograms;
public class ForEachStringEx {
public static void main(String[] args) {
// Create an array of string elements.
String[] names = {"John", "Amit", "Sara"};
// Iterating over each string element.
for (String n : names) {
System.out.println(n);
}
}
}Output:
John
Amit
SaraExample 3: Iterating Over Collections
package javaPrograms;
import java.util.ArrayList;
import java.util.List;
public class ForEachListEx {
public static void main(String[] args) {
// Create a list object.
List<String> cities = new ArrayList<>();
// Adding elements.
cities.add("New York");
cities.add("London");
cities.add("Tokyo");
cities.add("Paris");
// Iterating over elements of list.
for (String city : cities) {
System.out.println(city);
}
}
}Output:
New York
London
Tokyo
ParisExample 4: For-Each With Custom Objects in a Collection
package javaPrograms;
import java.util.ArrayList;
import java.util.List;
class Student {
private String name;
private int grade;
public Student(String name, int grade) {
this.name = name;
this.grade = grade;
}
// Applying getter methods.
public String getName() {
return name;
}
public int getGrade() {
return grade;
}
}
public class ForEachCustomObjectEx {
public static void main(String[] args) {
// Using for-each with custom objects
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 92));
students.add(new Student("Charlie", 78));
// Iterating using enhanced for-each loop
for (Student student : students) {
System.out.println(student.getName() + ": " + student.getGrade());
}
}
}Output:
Alice: 85
Bob: 92
Charlie: 78In this example, we have created a class named Student, which contains two private fields (variables) name and grade. The variable name stores the student’s name, while the variable grade stores student’s grade. Since both variables are private which ensures encapsulation, meaning data is protected from direct modification.
The constructor initializes the name and grade fields. The getter methods retrieve the values of private variables. The getName() method returns the student’s name, while the getGrade() method returns the student’s grade.
Then, we have created a list of student objects. ArrayList is used to store multiple Student objects. Three Student objects are added to the list:
- Alice with grade 85
- Bob with grade 92
- Charlie with grade 78
The enhanced for loop iterates over each Student object in the list. For each student:
- student.getName() retrieves the name.
- student.getGrade() retrieves the grade.
The program prints the student’s name and grade in a readable format.
Practical Uses of For-Each Loop in Java
Developers today use the enhanced for loop a lot. Here are real-world scenarios:
- Iterating collections in APIs.
- Reading configuration values.
- Processing lists of objects, such as users, products, orders.
- Printing or logging elements.
- Iterating database records retrieved as lists.
- Accessing file contents in line-by-line processing.
- Looping over arrays in competitive coding or algorithm problems.
Its readability and simplicity make it ideal for clean, maintainable code.
Difference Between For Loop and For-Each in Java
The basic differences between for loop and for-each loop in Java is given in the table:
| Aspect | For loop | For-each loop |
|---|---|---|
| Syntax | for(int i=0; i<length; i++) | for(Element element : collection) |
| Index Access | Direct access via index | No index access |
| Modification | You can modify collection during iteration. | You cannot modify collection during iteration. |
| Performance | Slightly faster for arrays | Comparable for most use cases |
| Readability | More verbose | More concise and readable |
| Error-Prone | More prone to off-by-one errors | Less error-prone |
When to Use For-Each Loop and For Loop in Java?
1. Use the For-Each Loop when:
- You only need to read the elements.
- The index is not required.
- You are working with arrays, lists, sets, or other iterable collections.
- You want to write cleaner, and more readable code
- You do not need to modify the collection structure.
2. Use the Traditional For Loop when:
- The index value matters.
- You need conditional skipping some elements.
- You need to iterate in reverse order.
- You need to modify elements based on their index.
- You need to remove or insert elements during iteration.
- You need more control over the loop execution.
FAQs on For-Each Loop in Java
1. Can we update array values using for-each loop?
Answer: No, you cannot update array elements directly inside a for-each loop.
2. Is for-each loop faster than the traditional for loop?
Answer: The traditional for loop may be slightly faster when iterating over primitive arrays, because it eliminates some of the overhead used internally by the enhanced for-each loop. However, when working with collections, the performance difference between the for loop and the for-each loop is almost negligible, and both perform nearly the same.
3. Can for-each loop be used with Maps?
Answer: Yes, we can use for-each loop using entrySet(), keySet(), or values().
4. Does for-each work with custom objects?
Answer: Yes, if the class implements Iterable.
5. When was for-each loop introduced in Java?
Answer: In Java 5 (JDK 1.5).
Conclusion
The for-each loop in Java is a powerful loop construct that allows you to write a clean way to iterate over elements of arrays and collections. Its simplicity, readability, and reduced chance of error make it a very popular looping construct in Java development. We hope that you will have understood the basic syntax of using for-each loop in Java and practiced all examples based on it.





