View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

For-each Loop in Java: A Beginner-Friendly Guide with Examples

Updated on 04/06/20255,847 Views

In Java, looping through elements is a task you often perform while building applications. Whether you are processing an array of numbers or displaying items from a list, loops help repeat actions efficiently. The for-each loop makes this process simpler and easier to read.

Instead of worrying about index values or running into errors like ArrayIndexOutOfBoundsException, you can directly access each element. It is like scrolling through photos in your gallery without counting how many you have seen.

This blog will explain what the For-Each Loop in Java is, how it works, its syntax, when to use it, when to avoid it, and common use cases. 

Software engineering courses can help you understand these concepts through structured learning and hands-on practice.

What is For-Each Loop in Java?

The for-each loop (also called an enhanced for loop) was introduced in Java 5. It allows you to iterate through arrays and collections without using an index. Think of it like scanning every item in a list, one by one, without checking its position.

Syntax:

for (dataType variable : arrayOrCollection) {
    // loop body
}

Example:

int[] numbers = {1, 2, 3};
for (int num : numbers) {
    System.out.println(num);
}

Output:

1

2

3

Explanation: Each element from the array is printed. No index is needed.

Unlock a high-paying career with the following full-stack development courses: 

When to Use For-Each Loop in Java

Use a for-each loop when you want to access every element one by one without modifying the structure or needing an index.

Example:

List<String> cities = List.of("Delhi", "Mumbai", "Bangalore");
for (String city : cities) {
    System.out.println(city);
}

Output:

Delhi  

Mumbai  

Bangalore

Explanation: Ideal for read-only iteration of all elements.

Must read: Java ArrayList forEach

When to Avoid For-Each Loop in Java 

The for-each loop is not suitable in certain situations. Avoid using it if you need to:

  • Access elements by their index: For-each does not provide access to the current element’s index, making it impossible to perform index-based operations. Use a traditional for loop instead.
  • Remove elements while iterating: Removing elements inside a for-each loop can cause errors like ConcurrentModificationException. Use an Iterator for safe removal.
  • Traverse the collection or array in reverse order: For-each always iterates forward, so reverse traversal requires a standard for loop.
  • Modify the original array or list elements directly: Since the loop variable holds a copy, modifying it won’t change the actual array or list element. Use a regular for loop to update elements.

Example:

int[] nums = {10, 20, 30};
for (int num : nums) {
    num = num + 5;
}
System.out.println(nums[0]);

Output:

10

Explanation: Modifying the loop variable doesn't affect the original array.

Must explore: Control Statements in Java: What Do You Need to Know in 2025

For-Each Loop with Arrays

Arrays are one of the most common structures used with for-each loops in Java.

Example – Finding Maximum:

int[] numbers = {5, 3, 9, 1, 7};
int max = numbers[0];
for (int num : numbers) {
    if (num > max) {
        max = num;
    }
}
System.out.println("Maximum: " + max);

Output:

Maximum: 9

Explanation: The loop checks each value to find the maximum.

Must explore: Comprehensive Guide to Exception Handling in Java

For-Each Loop in Java with Collections

Java collections like List and Set are compatible with for-each loops.

Example:

List<String> animals = List.of("Cat", "Dog", "Elephant");
for (String animal : animals) {
    System.out.println(animal);
}

Output:

Cat  

Dog  

Elephant

Explanation: Each item in the list is printed without needing an index.

Also read: How to Iterate Any Map in Java?

For-Each Loop with Map (Using Entry Set)

Maps can’t be used directly with for-each. But you can loop through their entrySet().

Example:

Map<String, Integer> scores = Map.of("Alisha", 90, "Bhanu", 85);
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Output:

Alisha: 90  

Bhanu: 85

Explanation: We iterate through key-value pairs using entrySet().

Also explore: Factorial Using Recursion in Java

For-Each Loop vs Traditional For Loop

Use traditional for loop when:

  • You need index access
  • You want reverse order
  • You want to modify items

Traditional For Loop in Java:

int[] data = {10, 20, 30};
for (int i = 0; i < data.length; i++) {
    System.out.println(data[i]);
}

For-Each Loop in Java:

for (int value : data) {
    System.out.println(value);
}

Both have their place in Java programming.

Enhanced For-Each Loop with Java Streams

Java 8 introduced the .forEach() method with Streams for functional-style coding.

Example:

List<String> names = List.of("Jhanvi", "Jiya", "Alisha");
names.forEach(name -> System.out.println(name));

Output:

Jhanvi 

Jiya  

Alisha

Explanation: A lambda expression prints each name from the Java stream.

Also read: Do While Loop in Java: Syntax, Examples, and Practical Applications

Use Cases and Real-World Applications of For-each Loop

The for-each loop is widely used in Java applications where simple, readable iteration is required without modifying the collection. Below are some common use cases and real-world applications. Let’s understand how For-each Loop in Java is used in real-world. 

1. Displaying Items from Databases

When fetching data from a database, results are often stored in a list or array. A for-each loop helps in displaying these records easily.

List<String> employees = Arrays.asList("Jiya", "Meera", "Amit");

for (String employee : employees) {
    System.out.println("Employee Name: " + employee);
}

Output:

Employee Name: Jiya

Employee Name: Meera

Employee Name: Amit

Explanation: Each record is accessed one by one without the need for indexes.

2. Validating Input Fields

For-each loops are useful when checking a list of user inputs for empty or invalid values.

String[] inputs = {"email", "password", ""};

for (String input : inputs) {
    if (input.isEmpty()) {
        System.out.println("One of the input fields is empty");
    }
}

Output:

One of the input fields is empty

Explanation: You can quickly validate all entries without managing index positions.

3. Showing Options in Dropdowns

When you have a list of options for dropdowns, for-each can render them in user interfaces.

String[] countries = {"India", "USA", "Germany"};

for (String country : countries) {
    System.out.println("Dropdown Option: " + country);
}

Output:

Dropdown Option: India

Dropdown Option: USA

Dropdown Option: Germany

Explanation: Common in web and GUI applications to list available options.

4. Analyzing Arrays of Sensor Data

For-each is ideal for processing large arrays of sensor data, like temperature or pressure readings.

double[] temperatures = {98.6, 101.2, 97.5};

for (double temp : temperatures) {
    if (temp > 100.0) {
        System.out.println("High temperature alert: " + temp);
    }
}

Output:

High temperature alert: 101.2

Explanation: Efficiently scans through each value to find outliers.

5. Printing Logs or Audit Trails

For-each loops help in printing log entries or audit records for system monitoring or debugging.

List<String> logs = Arrays.asList("Login success", "Password changed", "Logged out");

for (String log : logs) {
    System.out.println("Audit Log: " + log);
}

Output:

Audit Log: Login success

Audit Log: Password changed

Audit Log: Logged out

Explanation: You can loop through logs without needing to track log entry numbers.

Conclusion

The for-each loop in Java simplifies the process of iterating over arrays and collections by eliminating the need to manage indexes manually. It enhances code readability and reduces common errors like ArrayIndexOutOfBoundsException. While it is perfect for reading or processing elements, it has limitations such as not supporting element modification or index access. Knowing when to use or avoid it helps you write cleaner, safer, and more efficient Java programs that are easier to maintain and understand.

FAQs

1. Can I modify elements inside a for-each loop in Java?

No, you cannot modify original elements directly inside a for-each loop, especially for arrays or primitive types. The loop variable is a copy of the element, not a reference. To modify elements, use a traditional for loop with an index.

2. Can I use a for-each loop with a custom object array or list?

Yes, you can use a for-each loop with arrays or collections of custom objects. As long as the object is stored in an array or a class implementing the Iterable interface, the for-each loop works without any additional setup.

3. Is it possible to access the index of elements in a for-each loop?

No, the for-each loop does not expose the index of the current element. If you need index-based operations, use a traditional for loop. Alternatively, maintain a separate counter variable inside the for-each loop, but it requires manual incrementing.

4. Can I use a for-each loop on a Set in Java?

Yes, for-each loops can iterate over a Set because Set implements the Iterable interface. However, keep in mind that sets do not maintain any specific order, so the iteration order may not match the insertion or sorting sequence.

5. What happens if I try to remove elements from a collection using for-each?

Removing elements during a for-each loop using remove() causes a ConcurrentModificationException. The collection structure changes while iterating. To avoid this, use an Iterator with its remove() method, or collect elements separately and remove them after iteration.

6. Is for-each loop faster than a standard for loop?

For-each loops offer better readability but are not always faster. Traditional for loops may be more efficient for arrays, especially when index reuse or partial iteration is needed. The performance difference is minor and often not noticeable in real scenarios.

7. Can I iterate over multiple arrays or collections using a single for-each loop?

No, a single for-each loop can iterate over only one array or collection at a time. To iterate over multiple collections, you’ll need separate loops or merge them into one structure before iteration. Java doesn’t support multi-source for-each iteration.

8. Does for-each work with multidimensional arrays?

Yes, for-each loops support multidimensional arrays using nested loops. The outer loop accesses each sub-array, and the inner loop accesses elements of those sub-arrays. However, this approach assumes rectangular arrays where inner dimensions are consistent.

9. Is it safe to use for-each loop in multi-threaded environments?

For-each loops are not inherently thread-safe. If another thread modifies the collection during iteration, it may cause a ConcurrentModificationException. To avoid this, use concurrent collections or proper synchronization when accessing shared data in a multithreaded environment.

10. Can I break or continue inside a for-each loop?

Yes, Java allows the use of break and continue statements in a for-each loop. These help control the flow—break exits the loop, while continue skips the current iteration and moves to the next element in the collection.

11. Which interface allows a class to be used in a for-each loop?

Any class that implements the Iterable interface can be used in a for-each loop. This includes core collection classes like ArrayList, HashSet, and LinkedList, making for-each a convenient way to traverse these data structures.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.