Modifying Array Elements During Iteration
You'll learn how to safely update array values as you loop through them.
The Core Idea
When you iterate through an array, you often need to change the values stored inside it. The key is using an indexed loop (traditional for loop) that gives you the position of each element. With the index, you can both read the current value and write a new one using direct assignment.
Think of it like updating prices on shelf tags in a store. You walk down the aisle (iterate), check each price tag (read), and replace it with a new one (write) using the shelf position number (index).
Using Indexed Loops for Modification
You cannot modify array elements with an enhanced for-each loop because it only gives you a copy of each value, not access to the actual array slot. You must use a traditional for loop with an index:
int[] prices = {10, 20, 30, 40};
// Apply a 10% discount to all prices
for (int i = 0; i < prices.length; i++) {
prices[i] = prices[i] - 2; // Modify element at index i
}
// Now prices contains {8, 18, 28, 38}
The pattern is: arrayName[index] = newValue;
Why This Works
The index i tells Java exactly which slot in the array to update. When you write prices[i] = newValue, you're directly changing the contents of that memory location, not just a copy.
Another Example
int[] scores = {85, 92, 78, 88};
// Curve all scores by adding 5 points
for (int i = 0; i < scores.length; i++) {
scores[i] += 5; // Shorthand for scores[i] = scores[i] + 5
}
Key Takeaway: To modify array elements during iteration, use a traditional indexed for loop and assign directly to array[index] — enhanced for-each loops cannot modify the original array.