top

Search

Java Tutorial

.

UpGrad

Java Tutorial

For Each Loop in Java

Introduction

For each loop in Java is a technique to traverse multiple arrays and collections. For each loop in Java is mainly used to iterate through array and collection elements and provides the advantages of eliminating bugs and errors in codes to present it in a more convenient form. It is also known as the enhanced for loop Java ArrayList because it functions with array and collection elements.

Java for each loop traverses all elements one by one, and as it does not function on an index basis, you cannot skip any element. Java for each loop is increasingly used because it helps to draft the codes in a way that is user readable.

Overview

This is a detailed tutorial that will walk you through the concept of for each loop in Java. It will also dicuss the differences between “for each” loop and “for” loop. 

For Each Loop in Java

For each or “for-each” loop is used in Java, PHP, Python, etc, to traverse arrays and collections. It is a traversing technique program that is used in decision-making. The program starts with the keyword 'for.’ After that, you declare a variable of the same data type and specify the array name at the end. It is mainly used for iteration and traversing purposes and works well with ArrayList and collections.

For Each Loop in Java Syntax

Java for each loop syntax is:

for (type var : array) 
{ 
    statements using var;
}

Here's a breakdown of the different components:

  • type: The data type of the elements in the array or collection. For example, intStringObject, etc.

  • var: A variable that represents the current element being iterated.

  • array: The array or collection that you want to iterate over.

How Does It Work?

For each loop example: Traversing the array elements

public class main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        // Using for each loop to traverse the array elements
        for (int number : numbers) {
            System.out.println(number);
        }
    }
}

In this example, we have an array called numbers containing five elements. We use the "for each" loop to iterate over each array element. The loop variable number takes the value of each element in the array, and we print it using System.out.println().

For Each Loop Example: Traversing the Collection Elements

import java.util.ArrayList;
import java.util.List;
public class main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");
        // Using for each loop to traverse the collection elements
        for (String name : names) {
            System.out.println(name);
        }
    }
}

In this example, we have a List collection called names that stores strings. We use the "for each" loop to iterate over each element in the collection. The loop variable name takes the value of each element in the collection, and we print it using System.out.println().

When to Use Java For Each Loop?

You should use for each loop when you want to run a successful loop through all the values in a list or array. When you do not wish to change any values in the loop or remove anything, then using for each loop is the best way.

When Not to Use For Each Loop?

You should not use for each loop in Java when you want to perform the function of filtering. To filter, the program should have access to the iterator, but in the case of Java for each loop, the iterator is hidden. Hence, you should avoid using this program while trying to filter. Also, you cannot call remove because the iterator is hidden, so you should not use it for loops where you want to remove or replace elements in an ArrayList.

Flow Diagram of for each Loop in Java

Examples of For Each Loop in Java

Let's look at some real-world applications of the concept with Java for each loop example:

For Each Loop to Iterate Over Array Elements

public class Main {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Orange"};
        // Using for each loop to iterate over the array elements
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

In this example, we have an array called fruits containing three elements. We use the "for each" loop to iterate over each element in the array. The loop variable fruit takes the value of each element in the array, and we print it using System.out.println().

For Each Loop to Iterate Over HashMap

import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> hashMap = new HashMap<>();
        // Add some key-value pairs
        hashMap.put(1, "Apple");
        hashMap.put(2, "Banana");
        hashMap.put(3, "Orange");
        hashMap.put(4, "Mango");
        // Iterate over the HashMap using for each loop
        for (Map.Entry<Integer, String> entry : hashMap.entrySet()) {
            int key = entry.getKey();
            String value = entry.getValue();
            System.out.println("Key: " + key + ", Value: " + value);
        }
    }
}

In this example, we create a HashMap called hashMap and add some key-value pairs to it. Then, we use a for each loop to iterate over the entrySet() of the HashMap. Each entry in the entrySet() represents a key-value pair in the HashMap. Inside the loop, we retrieve the key and value of each entry using the getKey() and getValue() methods, respectively.

For Each Loop for Traversing a List of Elements

import java.util.ArrayList;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        // Create a list of custom objects
        List<Person> people = new ArrayList<>();
        // Add some people to the list
        people.add(new Person("John", 25));
        people.add(new Person("Alice", 30));
        people.add(new Person("Bob", 28));
        people.add(new Person("Emily", 22));
        // Traverse the list using for each loop
        for (Person person : people) {
            // Perform operations on each person
            String name = person.getName();
            int age = person.getAge();
            // Print the person's information
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Is Adult: " + (age >= 18));
            System.out.println("------------------------");
        }
    }
}
class Person {
    private String name;
    private int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

In this example, we have a custom class called Person that represents a person with a name and age. We create a List called people and add some Person objects to it.

Using a for each loop, we iterate over each Person object in the people list. Inside the loop, we retrieve the person's name and age using the getName() and getAge() methods. Then, we perform some operations on the person, such as determining if they are an adult based on their age.

Finally, we print the person's information, including their name, age, and whether they are adults. A line separates each person's information.

Advantages of For Each Loop in Java

Java for each loop is a convenient traversing and iteration technique for users. It has the following advantages to offer:

  • It removes the possibility of major programming errors and bugs.

  • The code for “for each” loop is easier to read and understand.

  • It does not use an index or counter in its loop.

Limitations of For Each Loop in Java

Some of the limitations that are there when using for each loop in Java are stated as follows:

  • It does not possess the ability to traverse through the elements in reverse order.

  • It does not allow the user to skip any element, as the concept of an index is absent.

  • It also prohibits the users from traversing to odd or even elements.

Difference Between For Loop and For Each Loop in Java

For loop

For each loop

For loops runs and executes a set of code until the result is returned as false.

For each loop executes a set of code through each element in an ArrayList or collection.

For loops are independent of any object or object collection and can run code with or without it.

The for each loop can execute codes only with object collection and not without it.

For loop is a general loop and can be used for various purposes.

for each loop is exclusively intended to operate with Collections or IEnumerables objects.

Conclusion

For each loop in Java is a valuable control flow statement that is used in traversing items or objects in a collection. It helps reduce errors and bugs in a program and creates an iterative system in programming. By learning the functionality and importance of Java for each loop, developers can use it efficiently to run programming codes while minimizing the possibility of errors. You can learn more about Java loops and other concepts from curated courses offered by online learning platforms like upGrad.

FAQs

1. Does Python have a for each loop?

There is no exclusive for each loop in Python. However, Python consists of two main loops: for loop and while loop. 

2. What is the for each loop in PHP?

For each loop in PHP is the same as that in Java and performs the same functions. It allows users to iterate objects in an array list or collection.

3. What is the importance of for each loop in Java?

For each loop is a decision-making statement that allows users to do away with the possibility of errors and bugs in a program and also performs traversing action.

Leave a Reply

Your email address will not be published. Required fields are marked *