Enhanced for loop in Java, also known as the for-each loop, provides a clean and readable way to iterate over arrays and collections. Instead of manually managing loop counters and index variables, Java automatically retrieves each element from the collection or array during iteration.
This approach reduces boilerplate code and improves readability, especially when working with Java collections such as ArrayList, LinkedList, and HashSet. In this guide, we will explore how the enhanced for loop works, its syntax, practical use cases, and situations where it should or should not be used.
Quick Reference Table
| Scenario | Example |
|---|---|
| Iterate over array | for (int n : numbers) |
| Iterate over ArrayList | for (String name : names) |
| Iterate over Set | for (String item : set) |
| Iterate over Map entries | for (Map.Entry<K,V> e : map.entrySet()) |
| Get size of list | list.size() |
| Length of array | array.length |
| Skip element in loop | continue |
| Stop loop early | break |
What is Enhanced For Loop in Java
The enhanced for loop is a simplified loop structure introduced in Java 5 to make iteration over arrays and collections easier and more readable.
Before Java 5, developers typically used a traditional loop with an index variable. The enhanced loop eliminates the need to manage indexes manually and instead focuses on the elements themselves.
The enhanced loop works with:
- Arrays
- Collections (
ArrayList,LinkedList,HashSet) - Any object implementing the
Iterableinterface
Because it removes index handling, it helps prevent common programming errors such as index overflow or incorrect loop conditions.
Syntax of Enhanced For Loop
The basic syntax of the enhanced loop is:
for (dataType variable : collection) {
// statements
}Where:
dataTyperepresents the type of elements storedvariablestores each element during iterationcollectionis the array or iterable object
Example:
int[] numbers = {1,2,3,4,5};
for (int num : numbers) {
System.out.println(num);
}During execution, Java automatically assigns each element of the array to the variable num.
Iterate Over Arrays
Arrays are the most common place where enhanced loops are used.
Example: printing all values from an array.
int[] numbers = {10,20,30,40};
for (int number : numbers) {
System.out.println(number);
}Example: calculating the sum of elements.
int[] values = {5,10,15,20};
int sum = 0;
for (int value : values) {
sum += value;
}
System.out.println("Total sum = " + sum);Because the loop directly accesses array elements, the code becomes simpler than using an index.
Iterate Over Java Collections
The enhanced loop works with any collection implementing the Iterable interface.
ArrayList
ArrayList is one of the most commonly used collections.
import java.util.ArrayList;
ArrayList<String> cities = new ArrayList<>();
cities.add("London");
cities.add("Paris");
cities.add("Tokyo");
for (String city : cities) {
System.out.println(city);
}This loop retrieves each element from the list sequentially.
LinkedList
LinkedList stores elements as nodes connected through references.
import java.util.LinkedList;
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(100);
numbers.add(200);
numbers.add(300);
for (int num : numbers) {
System.out.println(num);
}HashSet
HashSet stores unique elements and does not maintain order.
import java.util.HashSet;
HashSet<String> languages = new HashSet<>();
languages.add("Java");
languages.add("Python");
languages.add("Go");
for (String lang : languages) {
System.out.println(lang);
}Iterate Over Map
Maps cannot be iterated directly because they store key-value pairs. Instead, we iterate through the entry set.
import java.util.HashMap;
import java.util.Map;
Map<String,Integer> scores = new HashMap<>();
scores.put("Alice",90);
scores.put("Bob",85);
scores.put("Charlie",95);
for (Map.Entry<String,Integer> entry : scores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + " : " + score);
}This allows us to access both keys and values during iteration.
Working with Custom Objects
Enhanced loops are also commonly used with collections containing custom objects.
Example class:
class Student {
String name;
int marks;
Student(String name,int marks) {
this.name = name;
this.marks = marks;
}
}Using the enhanced loop:
import java.util.ArrayList;
ArrayList<Student> students = new ArrayList<>();
students.add(new Student("John",85));
students.add(new Student("Emma",90));
for (Student s : students) {
System.out.println(s.name + " scored " + s.marks);
}This approach is commonly used in real applications where objects are stored inside lists.
Enhanced For Loop vs Traditional For Loop
| Feature | Traditional Loop | Enhanced Loop |
|---|---|---|
| Requires index variable | Yes | No |
| Code readability | Moderate | High |
| Access index | Yes | No |
| Modify collection | Possible | Limited |
Traditional loop example:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}Enhanced loop equivalent:
for (int num : numbers) {
System.out.println(num);
}When NOT to Use Enhanced For Loop
Enhanced loops should not be used when:
- You need the index of elements
- You must remove or modify elements during iteration
- You need reverse iteration
Example requiring index:
for (int i = 0; i < list.size(); i++) {
System.out.println(i + " -> " + list.get(i));
}Java List Size vs Array Length (Quick Guide)
Understanding how to determine collection size is important when working with loops.
| Structure | Method |
|---|---|
| Array | array.length |
| ArrayList | list.size() |
| LinkedList | list.size() |
| HashSet | set.size() |
Example:
int[] numbers = {1,2,3,4};
System.out.println(numbers.length);
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
System.out.println(names.size());Arrays use a property, while collections use a method.
Common Errors with Enhanced For Loop
ConcurrentModificationException
This error occurs when modifying a collection during iteration.
Incorrect:
for (int num : numbers) {
numbers.remove(num);
}Correct approach:
Use an iterator or traditional loop.
Attempting Index Access
Enhanced loops do not expose indexes.
Incorrect:
for (int num : numbers) {
System.out.println(numbers[num]);
}Correct:
for (int num : numbers) {
System.out.println(num);
}Frequently Asked Questions
1. What is enhanced for loop in Java?
The enhanced for loop in Java, also known as the for-each loop, is a simplified way to iterate over arrays and collections without using index variables.2. When should I use the enhanced for loop in Java?
You should use the enhanced for loop when you need to read elements from an array or collection sequentially without modifying its structure.3. Can I modify a collection inside an enhanced for loop?
No, modifying a collection while iterating with an enhanced for loop can cause a ConcurrentModificationException. Use an Iterator or traditional loop instead.4. What is the difference between for loop and foreach loop in Java?
A traditional for loop uses an index to access elements, while the enhanced for loop directly iterates over elements in arrays or collections, making the code shorter and easier to read.5. Can enhanced for loop be used with Map in Java?
Maps themselves are not directly iterable, but you can iterate over map entries, keys, or values using methods like entrySet(), keySet(), or values() with an enhanced for loop.Summary
The enhanced for loop in Java simplifies iteration over arrays and collections by removing the need for index variables. It improves readability, reduces coding errors, and is widely used when sequentially processing elements.
In this guide, we explored how the enhanced loop works, its syntax, and practical examples involving arrays, collections, maps, and custom objects. Understanding when to use and when to avoid the enhanced loop helps developers write cleaner and more maintainable Java code.



