Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
15: The Enhanced For Loop
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
packageWeightswith 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
There are no comments for now.