Course contentsShow
← Java
Lesson 1296 of 2,87029. Iterators and IterableFree lesson

Enhanced For Loop vs Traditional For Loop

Comparing performance and use cases: when to prefer enhanced for and when to use indexed loops.

Enhanced For Loop vs Traditional For Loop

What you'll learn: When to choose the clean enhanced for loop and when you need the power of an indexed traditional for loop.

Both loop styles iterate over collections, but they excel in different scenarios. Understanding their trade-offs helps you write clearer, more efficient code.

Core Differences

The enhanced for loop (for-each) shines when you need simple, sequential access to every element without caring about position:

List<String> names = List.of("Alice", "Bob", "Charlie");

// Enhanced for: clean, safe, no index management
for (String name : names) {
    System.out.println(name);
}

The traditional indexed for loop is necessary when you need:

  • Access to the index itself
  • Partial iteration (skip elements, custom step sizes)
  • Backward traversal
  • Modifying the list structure (removing elements safely)
  • Parallel iteration over multiple collections
// Traditional for: index access and control
for (int i = 0; i < names.size(); i++) {
    System.out.println(i + ": " + names.get(i));
}

// Backward traversal
for (int i = names.size() - 1; i >= 0; i--) {
    System.out.println(names.get(i));
}

Performance Considerations

For ArrayList, both approaches have similar performance—O(1) indexed access makes traditional loops efficient. The enhanced for loop uses an iterator under the hood, adding negligible overhead.

For LinkedList, the traditional indexed loop can be dramatically slower (O(n²) total time) because each get(i) call traverses from the start. The enhanced for loop uses the iterator efficiently (O(n)).

Think of it this way: The enhanced for loop is like walking through a museum with a guide (iterator) who knows the path. The traditional loop is like asking "show me item #5" repeatedly—fast in a warehouse (ArrayList), slow in a winding corridor (LinkedList).

Key Takeaway: Prefer the enhanced for loop for simple sequential access; use the traditional indexed loop when you need position information, backward iteration, or index-based logic.