Course contentsShow
← Java
Lesson 172 of 2,8704. Control Flow StructuresFree lesson

Enhanced for Loop Limitations: No Index or Modification

Understand when you cannot use enhanced for loops: when needing the index or modifying the collection.

Enhanced for Loop Limitations: No Index or Modification

What You'll Learn

You'll discover the two major situations where you cannot use the enhanced for loop and must stick with a traditional for loop instead.

The Core Limitations

The enhanced for loop (for-each) is wonderfully simple, but that simplicity comes with trade-offs. There are two critical things it doesn't give you:

1. No Access to the Index

The enhanced for loop doesn't provide the current position (index) of the element you're processing. If you need to know "which element number am I on?" or need to access neighboring elements, you're out of luck.

When you need the index:

int[] scores = {85, 92, 78, 90};

// Enhanced for loop - NO index available
for (int score : scores) {
    // How do I print "Score #1 is 85"? I can't!
    System.out.println(score);
}

// Traditional for loop - index available
for (int i = 0; i < scores.length; i++) {
    System.out.println("Score #" + (i + 1) + " is " + scores[i]);
}

2. No Modification of the Collection Structure

The enhanced for loop gives you a copy of each element's value. You cannot use it to change which elements exist in the array or modify the array itself (though you can modify object properties if the elements are objects).

int[] numbers = {1, 2, 3, 4};

// This changes the COPY, not the array!
for (int num : numbers) {
    num = num * 2;  // numbers array is unchanged!
}

Analogy: The enhanced for loop is like reading names off flashcards—you see each name, but you can't renumber the cards or replace them.

Key Takeaway: Use traditional for loops when you need the index position or need to modify the collection itself; the enhanced for loop is read-only and index-blind.