Java For Each Loop

Welcome to The Coding College! In this tutorial, we’ll explore the for-each loop in Java. The for-each loop, also known as the enhanced for loop, simplifies iterating over arrays and collections.

What is the For-Each Loop?

The for-each loop is a special type of loop designed for iterating over elements in an array or collection. It eliminates the need for managing an index variable, making the code cleaner and easier to read.

Syntax

for (dataType element : array) {
    // Code to be executed for each element
}
  • dataType: The type of the elements in the array or collection.
  • element: A temporary variable to hold the current item in the array.
  • array: The array or collection to be iterated.

Example 1: Iterating Over an Array

Code

public class ForEachExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int num : numbers) {
            System.out.println("Number: " + num);
        }
    }
}

Output

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

Example 2: Iterating Over a String Array

Code

public class StringArrayExample {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry"};

        for (String fruit : fruits) {
            System.out.println("Fruit: " + fruit);
        }
    }
}

Output

Fruit: Apple  
Fruit: Banana  
Fruit: Cherry

Example 3: Using For-Each with a Collection

The for-each loop works seamlessly with Java Collections like ArrayList and HashSet.

Code

import java.util.ArrayList;

public class ForEachWithCollection {
    public static void main(String[] args) {
        ArrayList<String> cities = new ArrayList<>();
        cities.add("New York");
        cities.add("Los Angeles");
        cities.add("Chicago");

        for (String city : cities) {
            System.out.println("City: " + city);
        }
    }
}

Output

City: New York  
City: Los Angeles  
City: Chicago

Example 4: Iterating Over a 2D Array

The for-each loop can also be used with multi-dimensional arrays.

Code

public class TwoDArrayExample {
    public static void main(String[] args) {
        int[][] matrix = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };

        for (int[] row : matrix) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}

Output

1 2 3  
4 5 6  
7 8 9

Example 5: Limitations of the For-Each Loop

While the for-each loop is great for reading elements, it doesn’t allow:

  • Modifying elements in the array directly.
  • Accessing the index of the elements.

Example: Modifying Array Elements

public class ModifyArray {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};

        for (int num : numbers) {
            num *= 2; // Modifies only the local copy
        }

        for (int num : numbers) {
            System.out.println("Number: " + num); // Original values remain unchanged
        }
    }
}

Output:

Number: 1  
Number: 2  
Number: 3  
Number: 4  
Number: 5

To modify elements, use a traditional for loop with an index.

Practice Problems

  1. Write a program to calculate the sum of elements in an integer array using a for-each loop.
  2. Create a program to count the number of vowels in a string array.
  3. Use a for-each loop to print all elements of a 3D array.

Conclusion

The for-each loop is a concise and user-friendly way to iterate over arrays and collections. It simplifies code and minimizes the risk of errors, especially when you don’t need to modify the elements or access their indices.

Explore more Java tutorials at The Coding College and elevate your programming skills! 🚀

Leave a Comment