Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Java

Mastering the Java Enhanced For Loop: Syntax, Examples, and Best Practices

Mastering the Java Enhanced For Loop

Learn how the Java enhanced for loop simplifies iteration over arrays and collections, with clear examples and a side‑by‑side comparison to the classic for loop.

The enhanced for loop—often called the for‑each loop—is a staple in modern Java (introduced in JDK 1.5). It allows developers to iterate over arrays, Lists, and other collections with minimal boilerplate, improving readability and reducing the risk of off‑by‑one errors.


Enhanced For Loop Syntax

The syntax is concise and expressive:

for (DataType element : arrayOrCollection) {
    // process element
}

Example 1: Printing Array Elements

// Print array elements
class Main {
    public static void main(String[] args) {
        int[] numbers = {3, 9, 5, -5};
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

Output

3
9
5
-5

Each iteration assigns the current array value to number, printing it to the console.


Example 2: Summing Array Elements

// Calculate the sum of all elements in an array
class Main {
    public static void main(String[] args) {
        int[] numbers = {3, 4, 5, -5, 0, 12};
        int sum = 0;
        for (int number : numbers) {
            sum += number;
        }
        System.out.println("Sum = " + sum);
    }
}

Output:

Sum = 19
IterationVariables
1number = 3
sum = 0 + 3 = 3
2number = 4
sum = 3 + 4 = 7
3number = 5
sum = 7 + 5 = 12
4number = -5
sum = 12 + (-5) = 7
5number = 0
sum = 7 + 0 = 7
6number = 12
sum = 7 + 12 = 19

Each loop iteration adds the current element to sum, culminating in the final total.


For Loop vs. Enhanced For Loop

While both loops achieve the same result, the enhanced for loop offers clearer syntax and eliminates manual index handling.

1. Classic For Loop

class Main {
    public static void main(String[] args) {
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (int i = 0; i < vowels.length; ++i) {
            System.out.println(vowels[i]);
        }
    }
}

Output:

a
e
i
o
u

2. Enhanced For Loop

class Main {
    public static void main(String[] args) {
        char[] vowels = {'a', 'e', 'i', 'o', 'u'};
        for (char vowel : vowels) {
            System.out.println(vowel);
        }
    }
}

Output:

a
e
i
o
u

Both produce identical output, but the enhanced for loop is more concise and less error‑prone. It is the recommended approach for iterating over arrays and collections in contemporary Java.

For more details, consult the official Java Tutorials.

Java

  1. Master Java Operators: Types, Syntax, & Practical Examples
  2. Master Java For Loops: Syntax, Examples, and Best Practices
  3. Mastering Java While & Do‑While Loops: Step‑by‑Step Tutorial
  4. Java Continue Statement – Mastering Loop Control with Examples
  5. Mastering Java's super Keyword: Advanced Usage & Practical Examples
  6. Mastering Java Interfaces: Concepts, Implementation, and Best Practices
  7. Mastering Java Try‑with‑Resources: Automatic Resource Management Explained
  8. Java Annotations Explained: Types, Placement, and Practical Examples
  9. Java For‑Each Loop: Simplifying Array Iteration Without Counters
  10. Mastering Java Loop Control: Efficient Repetition Techniques