🚀 Tech Hub

← Back to Tutorials

Java Enhanced For Loop Mistakes – Common Errors & Examples

The enhanced for loop (for-each loop) is easy to use but beginners often misuse the colon : or modify the array incorrectly.

1. Using Semicolons Instead of Colon

❌ Wrong Code

int[] nums = {1, 2, 3};
for (int n; nums) {  // ← Incorrect syntax
    System.out.println(n);
}
Error: error: ';' expected or illegal start of expression

✅ Correct Code

int[] nums = {1, 2, 3};
for (int n : nums) {  // ← Correct colon
    System.out.println(n);
}

2. Modifying Array Elements Inside Loop

Directly modifying elements in enhanced for can lead to unexpected behavior.

❌ Wrong Code

int[] nums = {1, 2, 3};
for (int n : nums) {
    n = n * 2;  // Doesn't change array elements
}

💡 Tip

Use a traditional for loop with index if you want to modify array elements.

✅ Correct Code with Index

int[] nums = {1, 2, 3};
for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 2;  // Proper modification
}