Skip to Content
Course content

15: The Enhanced For Loop

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this mistake constantly when I'm reviewing code from junior devs: they try to use the enhanced for loop to modify the contents of an array. They assume that because the loop is iterating through the collection, the loop variable is a direct "handle" to the slot in the array.

The Myth: You Can Update Array Elements Directly

Imagine you have an array of product prices and you want to apply a 10% discount to all of them. You might be tempted to write something like this:

double[] prices = {19.99, 25.50, 9.99, 45.00};

for (double price : prices) {
    price = price * 0.9; // Attempting to apply discount
}

// You'd expect the prices array to be updated here, but it's not.
System.out.println(prices[0]); // Still prints 19.99

It looks clean, right? But here is the problem: price is just a local copy of the value in the array. When you do price = price * 0.9, you are changing that local variable, not the actual element inside the prices array. The array remains untouched. I've spent more hours than I'd like to admit debugging "ghost bugs" caused by this exact misunderstanding.

The Reality: It's a Read-Only View of the Data

The enhanced for loop—often called the "for-each" loop—is designed for access, not mutation. It tells Java: "I want to look at every item in this collection, one by one, and I don't care about the index number."

If you actually need to change the values in the array, you must go back to the standard for loop because you need the index to target the specific memory slot. However, when you just need to process data—like calculating a sum or printing a list—the enhanced loop is vastly superior because it eliminates the "off-by-one" errors that happen when you mess up your i < array.length logic.

Here is how you use it correctly for reading data:

String[] guests = {"Alice", "Bob", "Charlie", "Diana"};

for (String guest : guests) {
    System.out.println("Welcome to the party, " + guest + "!");
}

In this case, we aren't trying to change the guests' names; we are just using them. This is where the enhanced loop shines. It reads like a sentence: "For each String guest in guests, do this."

When to Reach for the Standard Loop Instead

I generally follow a simple rule of thumb: default to the enhanced for loop unless you can answer "yes" to any of these three questions:

  • Do I need to modify the value at a specific index?
  • Do I need to know the current index (e.g., "Item #1", "Item #2")?
  • Do I need to iterate backwards or skip elements?

If any of those are true, the enhanced loop is the wrong tool for the job. If not, use it. It makes your code cleaner and tells whoever is reading your code later that you are simply traversing the list without messing with its structure.




📋 Practical Task

Calculating Total Order Weight for a Shipping Manifest

You are building a shipping module. You have an array of weights (in kilograms) for various packages in a single shipment. Your task is to calculate the total weight of the shipment to determine if it exceeds the aircraft's limit.

Write a program that:

  • Declares an array of doubles named packageWeights with the values: 12.5, 4.2, 18.9, 2.1, 7.7.
  • Uses an enhanced for loop to iterate through the weights and calculate the sum.
  • Prints the final total weight to the console.
// Your code here
Rating
0 0

There are no comments for now.

to be the first to leave a comment.