DEV Community

Rajesh Bhola
Rajesh Bhola

Posted on

Part 4: Enhanced `for` Loop (for-each)

In Part 1, we explored the while loop.

In Part 2, we learned about the do-while loop.

In Part 3, we covered the traditional for loop, which is perfect when the number of iterations is known.

In this final part, we'll learn about the Enhanced for Loop, also known as the for-each loop, introduced in Java 5.

This loop greatly simplifies iterating over arrays and collections by eliminating manual index management.


What Is the Enhanced for Loop?

The enhanced for loop is a simplified version of the traditional for loop.

It automatically retrieves each element from an array or an Iterable collection one by one.

Instead of writing index-based code, you focus directly on the element you're processing.


Why Was It Introduced?

Before Java 5, iterating over an array required managing indexes manually.

Example

String[] developers = {

    "Rajesh",
    "Anita",
    "Rahul"

};

for (int index = 0; index < developers.length; index++) {

    System.out.println(developers[index]);

}
Enter fullscreen mode Exit fullscreen mode

Java 5 introduced a cleaner alternative.

String[] developers = {

    "Rajesh",
    "Anita",
    "Rahul"

};

for (String developer : developers) {

    System.out.println(developer);

}
Enter fullscreen mode Exit fullscreen mode

Output

Rajesh
Anita
Rahul
Enter fullscreen mode Exit fullscreen mode

The code is shorter, cleaner, and less error-prone.


Syntax

for (DataType variable : collectionOrArray) {

    // use variable

}
Enter fullscreen mode Exit fullscreen mode

Where:

  • DataType is the element type.
  • variable represents the current element.
  • collectionOrArray is the array or collection being traversed.

How the Enhanced for Loop Works

For every iteration:

  1. Java retrieves the next element.
  2. Assigns it to the loop variable.
  3. Executes the loop body.
  4. Repeats until no elements remain.

You never manage indexes yourself.


Example: Iterating Over an Array

int[] marks = {

    80,
    90,
    95,
    88

};

for (int mark : marks) {

    System.out.println(mark);

}
Enter fullscreen mode Exit fullscreen mode

Output

80
90
95
88
Enter fullscreen mode Exit fullscreen mode

Example: Iterating Over a String Array

String[] teamMembers = {

    "Rajesh",
    "Priya",
    "Amit"

};

for (String member : teamMembers) {

    System.out.println(member);

}
Enter fullscreen mode Exit fullscreen mode

Output

Rajesh
Priya
Amit
Enter fullscreen mode Exit fullscreen mode

Example: Iterating Over an ArrayList

import java.util.ArrayList;
import java.util.List;

List<String> technologies = new ArrayList<>();

technologies.add("Java");
technologies.add("Spring Boot");
technologies.add("Kafka");

for (String technology : technologies) {

    System.out.println(technology);

}
Enter fullscreen mode Exit fullscreen mode

Output

Java
Spring Boot
Kafka
Enter fullscreen mode Exit fullscreen mode

What Can the Enhanced for Loop Iterate?

The enhanced for loop works with:

  • Arrays
  • Objects implementing Iterable

Examples include:

  • ArrayList
  • LinkedList
  • HashSet
  • TreeSet
  • LinkedHashSet
  • PriorityQueue

Understanding Iterable

The enhanced for loop works because many Java collections implement the Iterable interface.

Simplified definition:

public interface Iterable<T> {

    Iterator<T> iterator();

}
Enter fullscreen mode Exit fullscreen mode

Notice that Iterable contains only one method:

iterator()
Enter fullscreen mode Exit fullscreen mode

The compiler automatically uses this method behind the scenes.


What Happens Internally?

When you write

for (String technology : technologies) {

    System.out.println(technology);

}
Enter fullscreen mode Exit fullscreen mode

the compiler roughly converts it into

Iterator<String> iterator = technologies.iterator();

while (iterator.hasNext()) {

    String technology = iterator.next();

    System.out.println(technology);

}
Enter fullscreen mode Exit fullscreen mode

This is why the enhanced for loop works with every Iterable collection.


Arrays vs Collections

Arrays don't implement Iterable.

However, the Java compiler provides special support for arrays.

Therefore, both of these are valid.

Array

for (int number : numbers) {

    System.out.println(number);

}
Enter fullscreen mode Exit fullscreen mode

Collection

for (String name : names) {

    System.out.println(name);

}
Enter fullscreen mode Exit fullscreen mode

Limitations of the Enhanced for Loop

Although convenient, the enhanced for loop has several limitations.


Limitation 1: Cannot Access Indexes

Suppose you want both the index and the value.

Traditional for

for (int index = 0; index < teamMembers.length; index++) {

    System.out.println(index + " : " + teamMembers[index]);

}
Enter fullscreen mode Exit fullscreen mode

Enhanced for

for (String member : teamMembers) {

    // No index available

}
Enter fullscreen mode Exit fullscreen mode

Limitation 2: Cannot Traverse Backwards

Traditional for

for (int index = teamMembers.length - 1; index >= 0; index--) {

    System.out.println(teamMembers[index]);

}
Enter fullscreen mode Exit fullscreen mode

Enhanced for

Not possible.

Traversal is always from beginning to end.


Limitation 3: Cannot Skip Elements Easily

With a traditional for, you can increment by two.

for (int index = 0; index < numbers.length; index += 2) {

    System.out.println(numbers[index]);

}
Enter fullscreen mode Exit fullscreen mode

The enhanced for loop always visits every element.


Limitation 4: Not Suitable for General Counting

The enhanced for loop requires an array or an Iterable.

This is invalid.

for (int value : 10) {

}
Enter fullscreen mode Exit fullscreen mode

If you simply want to repeat something ten times, use a traditional for loop instead.


Modifying Elements

Changing the loop variable does not modify the original array.

int[] scores = {

    10,
    20,
    30

};

for (int score : scores) {

    score = score + 10;

}
Enter fullscreen mode Exit fullscreen mode

Output

10
20
30
Enter fullscreen mode Exit fullscreen mode

The array remains unchanged.

The loop variable is only a copy of each element.


Execution Trace

String[] names = {

    "Rajesh",
    "Priya",
    "Amit"

};

for (String name : names) {

    System.out.println(name);

}
Enter fullscreen mode Exit fullscreen mode
Iteration Current Element Output
1 Rajesh Rajesh
2 Priya Priya
3 Amit Amit

Common Beginner Mistakes

Expecting the Loop Variable to Modify the Array

Incorrect assumption

for (int number : numbers) {

    number++;

}
Enter fullscreen mode Exit fullscreen mode

The original array is unchanged.


Trying to Access the Index

Incorrect

for (String developer : developers) {

    System.out.println(index);

}
Enter fullscreen mode Exit fullscreen mode

There is no index variable.


Using It for Counting

Incorrect

for (int value : 100) {

}
Enter fullscreen mode Exit fullscreen mode

The enhanced for loop requires an array or an Iterable.


Traversing in Reverse

The enhanced for loop cannot traverse backwards.

Use a traditional for loop instead.


Iterable vs Iterator

Feature Iterable Iterator
Package java.lang java.util
Purpose Makes an object usable in a for-each loop Retrieves elements one by one
Main Method iterator() hasNext(), next(), remove()
Introduced Java 5 Java 1.2

Traditional for vs Enhanced for

Feature Traditional for Enhanced for
Uses index ✅ Yes ❌ No
Traverses backwards ✅ Yes ❌ No
Skip elements ✅ Yes ❌ No
Arrays ✅ Yes ✅ Yes
Collections ✅ Yes ✅ Yes
Readability Good Excellent

When Should You Use Each?

Use the traditional for loop when:

  • You need indexes.
  • You need reverse traversal.
  • You need custom increments.
  • You want to modify array elements.

Use the enhanced for loop when:

  • You simply want to read every element.
  • You don't care about indexes.
  • You want cleaner and more readable code.

Interview Questions

When was the enhanced for loop introduced?

Java 5.


Can it iterate over arrays?

Yes.

Arrays have built-in compiler support.


Can it iterate over collections?

Yes.

Collections implement Iterable.


Can you traverse backwards?

No.

Traversal is always from beginning to end.


Can you modify the original array through the loop variable?

No.

The loop variable receives a copy of each element.


What interface enables the enhanced for loop?

Iterable.


Best Practices

  • Use the enhanced for loop when you only need to read elements.
  • Use meaningful variable names like developer, student, or technology.
  • Switch to a traditional for loop whenever indexes are required.
  • Don't attempt to modify array elements through the loop variable.
  • Prefer readability over clever code.

Quick Memory Trick 🧠

Remember EACH:

  • E → Every element
  • A → Arrays and Iterable
  • C → Cleaner syntax
  • H → Hides indexes

Or simply remember:

"Need every element? Use for-each."


Key Takeaways

  • The enhanced for loop was introduced in Java 5.
  • It simplifies iteration over arrays and collections.
  • It works with arrays and objects implementing Iterable.
  • The compiler internally uses an Iterator for collections.
  • It cannot access indexes.
  • It cannot traverse backwards.
  • It cannot skip elements.
  • It is ideal when you only need to read every element.

If you found this guide helpful, leave a ❤️ and follow for more beginner-friendly Java tutorials, interview questions, and practical coding examples.

Happy Coding!

Top comments (0)