BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java For-each Loop (Enhanced for loop)

Last Updated: June 2, 2024 by Chaitanya Singh | Filed Under: java

In this guide, we will discuss for-each loop in detail with the help of examples. In Java, the for-each loop is used to iterate arrays or collections. It is easier to use than traditional for loop, this is why it is also known as enhanced for loop.

Syntax

Syntax of for-each loop:

for (Type element : collection) {
// Use element
}

Here, Type is the type of the elements in the collection, for example, int, String etc. The element is a variable that holds each element in the collection during each iteration, and collection is the array or collection that you want to iterate over.

Examples

Let’s see few examples where we are using for-each loop to iterate various collections.

Iterating Over an Array

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

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

Iterating Over an ArrayList

import java.util.ArrayList;
import java.util.List;

public class ForEachExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Mango");

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

Iterating Over a Set

import java.util.HashSet;
import java.util.Set;

public class ForEachExample {
public static void main(String[] args) {
Set<String> animals = new HashSet<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");

for (String animal : animals) {
System.out.println(animal);
}
}
}

Important Points to Note:

  1. Read-Only Access: While iterating a collection using for-each loop, you cannot modify the collection. This is because it gives you read-only access. For this purpose, we use Iterator, an example of this is at the end of this guide.
  2. Ease to use: It is simple and easier to use than normal for loop as we don’t need counter variable here.
  3. Performance: There are performance issues in certain cases, for example, if we want to access a particular element from a certain index of ArrayList, then it is not advisable to use for-each loop.

Limitations of for-each loop

  1. No Access to Index: Although it provides an easy way to iterate, it has certain limitations. For example, If you need the index of the current element, you cannot directly get it using the for-each loop. In such conditions, you would need to use a traditional for loop.
  2. Modification: As discussed earlier in “read-only access” section that you cannot modify a collection inside for-each loop during iteration. You would need to use Iterator, see the following example:

Modifying a Collection while iterating

To modify a collection during iteration, you would need to use Iterator as shown below. In the following example, we are removing an element from the list inside while loop.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ModifyExample {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("AA");
items.add("BB");
items.add("CC");

Iterator<String> iterator = items.iterator();
while (iterator.hasNext()) {
String item = iterator.next();

// Checking if the current element is "BB"
// and removing it if it matches
if (item.equals("BB")) {
iterator.remove();
}
}

System.out.println(items); // Output: [A, C]
}
}

Advantages of for-each loop:

  • It improves code readability, which reduces the chances of errors during iteration.
  • It takes care of the type-safety while iterating as it ensures that the type of element matches with the type of collection you want to iterate over.

Top Related Articles:

  1. How to sort Hashtable in java
  2. ValueOf() Method in Java
  3. Java Scanner class with examples
  4. Examples of throws Keyword in Java
  5. Constructor Overloading in Java with examples

Tags: Collections

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap

Advertisement