Java Enhanced For-Each Loop
The Enhanced `for-each` loop provides a clean, readable syntax to iterate sequentially through every element in an array or collection. It eliminates index math and completely prevents out-of-bounds bugs.
"A for-each loop is like a conveyor belt passing items to you one by one. You don't care what number slot it was in; you just pick up each item and process it."
Deep Dive: How It Works
Syntax: `for (type item : collectionOrArray) { /* use item */ }`
Read-only element access: Modifying `item` inside the loop does NOT change the value in the underlying array.
Use standard `for` loop if you need the numerical index `i` or need to modify array elements in-place.
Syntax Blueprint
for (String name : namesArray) {
System.out.println(name);
}Reads naturally: "For each String name in namesArray, do something".
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Trying to modify array values through the iteration variable: for (int x : arr) { x = 0; }Why it happens: x is a copy of the value; modifying x leaves the array unchanged.
How to fix: Use a standard index-based loop when modifying array elements: arr[i] = 0;.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Print prices with for-each loop
Given double[] prices = {9.99, 19.99, 4.99};
Use a for-each loop to print "Price: $" + p for each price.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.