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

Java For‑Each Loop: Simplifying Array Iteration Without Counters

When working with collections in Java, the for‑each loop offers a concise, readable alternative to the traditional indexed for loop. By eliminating manual index management, it reduces boilerplate and potential off‑by‑one errors.

Syntax

for (DataType element : collection) {
    // Process element
}

Practical Example

Below we iterate over a String array using both the conventional for loop and the for‑each loop to highlight the differences.

Array declaration:

String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};

Traditional for Loop

for (int i = 0; i < arrData.length; i++) {
    System.out.println(arrData[i]);
}

For‑Each Loop

for (String element : arrData) {
    System.out.println(element);
}

Notice that the for‑each version eliminates the index variable and makes the intent of “process each item” crystal clear.

Key Points to Remember

Complete Class Example

class UsingForEach {
    public static void main(String[] args) {
        String[] arrData = {"Alpha", "Beta", "Gamma", "Delta", "Sigma"};

        System.out.println("Using conventional For Loop:");
        for (int i = 0; i < arrData.length; i++) {
            System.out.println(arrData[i]);
        }

        System.out.println("\nUsing Foreach loop:");
        for (String element : arrData) {
            System.out.println(element);
        }
    }
}

Java For‑Each Loop: Simplifying Array Iteration Without Counters

Output

Using conventional For Loop:
Alpha
Beta
Gamma
Delta
Sigma

Using Foreach loop:
Alpha
Beta
Gamma
Delta
Sigma

Both loops produce identical results, but the for‑each loop achieves the same with less code and fewer chances for errors.

Java

  1. Master Java For Loops: Syntax, Examples, and Best Practices
  2. Mastering the Java Enhanced For Loop: Syntax, Examples, and Best Practices
  3. Mastering Java Arrays: Declaration, Initialization, and Manipulation
  4. C++ For Loops Explained: Syntax, Workflow, and Practical Examples
  5. Java For‑Each Loop: Simplifying Array Iteration Without Counters
  6. JasperReports for Java: Comprehensive Tutorial with Installation, Features, and Sample Report
  7. Java Program to Identify Armstrong Numbers Using For Loop
  8. Java Palindrome Number Checker: Algorithms Using While and For Loops
  9. Master Bubble Sort in Java: Clear Example & Step‑by‑Step Walkthrough
  10. Selection Sort in Java: Step‑by‑Step Example & Full Code