0
0
JavaHow-ToBeginner · 3 min read

How to Use Enhanced For Loop in Java: Syntax and Examples

The enhanced for loop in Java is used to iterate over arrays or collections easily without using an index. It has the syntax for (type item : collection) { }, where each item is accessed one by one from the collection.
📐

Syntax

The enhanced for loop syntax is:

for (type item : collection) {
    // use item
}

Here, type is the data type of elements, item is a variable holding each element, and collection is an array or any Iterable object.

java
for (int number : numbers) {
    System.out.println(number);
}
💻

Example

This example shows how to use the enhanced for loop to print all elements of an integer array.

java
public class EnhancedForLoopExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 40, 50};
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}
Output
10 20 30 40 50
⚠️

Common Pitfalls

Common mistakes include trying to modify the collection inside the loop or using the enhanced for loop when you need the index of elements.

Also, you cannot use the enhanced for loop with non-iterable objects.

java
/* Wrong: Trying to modify array elements directly */
int[] nums = {1, 2, 3};
for (int num : nums) {
    num = num * 2; // This does NOT change the original array
}

/* Correct: Use index-based loop to modify elements */
for (int i = 0; i < nums.length; i++) {
    nums[i] = nums[i] * 2;
}
📊

Quick Reference

  • Use enhanced for loop to read elements from arrays or collections.
  • Do not modify the collection structure inside the loop.
  • Use traditional for loop if you need element indexes.

Key Takeaways

Use enhanced for loop to simplify iteration over arrays and collections.
The syntax is: for (type item : collection) { }.
You cannot modify the original collection elements by assigning to the loop variable.
Use traditional for loop if you need the index of elements.
Enhanced for loop works only with arrays or Iterable objects.