The Wayback Machine - https://web.archive.org/web/20241127043127/https://www.geeksforgeeks.org/for-each-loop-in-java/
Open In App

For-each loop in Java

Last Updated : 26 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The for-each loop in Java (also called the enhanced for loop) was introduced in Java 5 to simplify iteration over arrays and collections. It is cleaner and more readable than the traditional for loop and is commonly used when the exact index of an element is not required.

Example:

Below is a basic example of using the for-each loop to iterate through an array and print each element. A for-each loop directly accesses elements without needing index variables.

Java
// Java Program to Iterate through an array
// Using for-each loop
import java.io.*;

class ForEach {
  
    public static void main(String[] args) {
      
        // Array declaration
        int arr[] = { 1, 2, 3, 4, 5 };
        
        // Using for-each loop to 
        // print each element
        for (int e : arr) {
            System.out.print(e + " ");
        }
    }
}

Output
1 2 3 4 5 

Explanation: In this example, the for-each loop iterates over the array “arr" and prints each element. We use the variable element "e" to access each value in the array, making the loop more concise compared to using a traditional for loop with an index.

Syntax of For-each Loop

for (type var : array) {

statements using var;

}

Parameters:

  • type: The data type of the elements in the array or collection.
  • var: The variable that holds the current element during each iteration.
  • array: The array or collection being iterated over.

The for-each loop is a cleaner way to iterate through arrays and collections in Java. To learn more about iterations and their use in complex scenarios, the Java Programming Course includes a detailed section on loops and iterations that will help deepen your understanding.

Finding Maximum in an Array using for-each Loop

Now, let’s go through another example that finds the maximum value in an integer array using a for-each loop.

Java
// Java Program to find maximum in an array
// Using for-each loop
public class Maximum {
  
    public static void main(String[] args) {
      
        int[] mark = {125, 132, 95, 116, 110};

        int max = findMax(mark);
        System.out.println("" + max);
    }

    public static int findMax(int[] n) {
        int maximum = n[0];

        // Iterates through the array
        for (int n1: n) {        
            if (n1 > maximum) {
                maximum = n1;
            }
        }
        return maximum;
    }
}

Output
132

Limitations of the For-each Loop

While the for-each loop is convenient, there are some important limitations to consider:

1. Cannot Modify Array Elements Directly

for (int num : marks) {

// only changes num, not the array element
num = num*2;

}

Explanation: The for-each loop gives a copy of each element, not a reference. So modifying the loop variable (num in this case) does not affect the actual array or collection.

2. No Access to Index

for (int num : numbers) {

if (num == target) {

// do not know the index of ‘num’ here

return ???; // Index is unavailable in for-each loop

}

}

Explanation: The for-each loop does not provide access to the index of the current element. If we need the index for any reason (e.g., in a search operation), a traditional loop would be more appropriate.

3. Single-direction Iteration Only

for (int i = numbers.length – 1; i >= 0; i–) {

System.out.println(numbers[i]); // Reverse iteration not possible with for-each

}

Explanation: The for-each loop only iterates over the elements in a forward direction. If we need to iterate in reverse, we have to use a traditional for loop with a manually managed index.

4. Complex Conditions are Difficult to Implement

for (int i = 0; i < numbers.length; i++) {

if (numbers[i] == arr[i]) {

// Complex conditional checks are easier in a traditional for loop

}

}

Explanation: If our logic requires checking multiple conditions or using the index in more complex ways, the for-each loop can be limiting. In such cases, a traditional for loop offers more flexibility.

5. Performance Overhead

List<Integer> list = new ArrayList<>();

for (int i = 0; i < 1000000; i++) list.add(i);


// Using for-each loop

long startTime = System.currentTimeMillis();

for (int i : list) { int a = i; }

long endTime = System.currentTimeMillis();

System.out.println(“For-each loop: ” + (endTime – startTime) + ” ms”);


// Traditional loop

startTime = System.currentTimeMillis();

for (int i = 0; i < list.size(); i++) { int a = list.get(i); }

endTime = System.currentTimeMillis();

System.out.println(“Traditional loop: ” + (endTime – startTime) + ” ms”);

Explanation: The performance of the for-each loop can be slightly worse compared to a traditional for loop, especially when working with large collections. This overhead comes from the iterator used by the for-each loop behind the scenes.

Example:

Java
// Java program to compare the performance of 
// different loop types for 
// iterating over a large list
import java.io.*;
import java.util.*;

class GFG {
    public static void main (String[] args) {
      
        List<Integer> list = new ArrayList<>();
        long startTime;
        long endTime;
        
        // Adding 1 million integers to the list
        for (int i = 0; i < 1000000; i++) {
            list.add(i);
        }

        // Type 1: Using a for-each loop
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int i : list) {
            int a = i;     // Looping over each element
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("For each loop :: " + (endTime - startTime) + " ms");
        
        // Type 2: Using list.size() in the loop condition
        startTime = Calendar.getInstance().getTimeInMillis();
        for (int j = 0; j < list.size(); j++) {
            int a = list.get(j);      // Accessing list elements using index
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms");
        
        // Type 3: Calculating the collection size before the loop
        startTime = Calendar.getInstance().getTimeInMillis();
        int size = list.size();     // Calculating size once
        for (int j = 0; j < size; j++) {
            int a = list.get(j);     // Accessing list elements using index
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms");
    
        // Type 4: Iterating the list in reverse order
        startTime = Calendar.getInstance().getTimeInMillis();
        for(int j = list.size()-1; j >= 0; j--) {
            int a = list.get(j);       // Accessing list elements in reverse
        }
        endTime = Calendar.getInstance().getTimeInMillis();
        System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms");
    }
}

Output
For each loop :: 85 ms
Using collection.size() :: 11 ms
By calculating collection.size() first :: 33 ms
Using [int j = list.size(); j > size ; j--] :: 19 ms

Points to Remember:

  • The loop starts with the keyword for like a normal for-loop.
  • Instead of declaring and initializing a loop counter variable, we declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.
  • In the loop body, we can use the loop variable we created rather than using an indexed array element.
  • It is commonly used to iterate over an array or a Collections class (e.g., ArrayList)
     


Previous Article
Next Article

Similar Reads

Difference Between for loop and Enhanced for loop in Java
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice. Syntax: for( initializationsection ; conditional check ; increment/decrement section) { // Code to be executed } Curly braces i
5 min read
Flatten a Stream of Lists in Java using forEach loop
Given a Stream of Lists in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: lists = [ [1, 2], [3, 4, 5, 6], [8, 9] ] Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: lists = [ ['G', 'e', 'e', 'k', 's'], ['F', 'o', 'r'] ] Output: [G, e, e, k, s, F, o, r] Approach: Get the Lists in the form of 2D list. Create an empty list t
3 min read
Flatten a Stream of Arrays in Java using forEach loop
Given a Stream of Arrays in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: arr[][] = {{ 1, 2 }, { 3, 4, 5, 6 }, { 7, 8, 9 }} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: arr[][] = {{'G', 'e', 'e', 'k', 's'}, {'F', 'o', 'r'}} Output: [G, e, e, k, s, F, o, r] Approach: Get the Arrays in the form of 2D array. Create an
3 min read
Flatten a Stream of Map in Java using forEach loop
Given a Stream of Map in Java, the task is to Flatten the Stream using forEach() method. Examples: Input: map = {1=[1, 2], 2=[3, 4, 5, 6], 3=[7, 8, 9]} Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] Input: map = {1=[G, e, e, k, s], 2=[F, o, r], 3=[G, e, e, k, s]} Output: [G, e, e, k, s, F, o, r] Approach: Get the Map to be flattened. Create an empty list to c
3 min read
Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Generic For Loop in Java
When we know that we have to iterate over a whole set or list, then we can use Generic For Loop. Java's Generic has a new loop called for-each loop. It is also called enhanced for loop. This for-each loop makes it easier to iterate over array or generic Collection classes. In normal for loop, we write three statements : for( statement1; statement 2
4 min read
String Array with Enhanced For Loop in Java
Enhanced for loop(for-each loop) was introduced in java version 1.5 and it is also a control flow statement that iterates a part of the program multiple times. This for-loop provides another way for traversing the array or collections and hence it is mainly used for traversing arrays or collections. This loop also makes the code more readable and r
1 min read
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with
7 min read
Infinite Loop Puzzles in Java
Problem 1 : Insert code in the given code segments to make the loop infinite. class GFG { public static void main(String s[]){ /* Insert code here */ for (int i = start; i <= start + 1; i++) { /* Infinite loop */ } } } Solution: It looks as though it should run for only two iterations, but it can be made to loop indefinitely by taking advantage
3 min read
How to Loop Over TreeSet in Java?
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.  Now the task
4 min read
Difference between while and do-while loop in C, C++, Java
while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. Syntax : while (boolean condition){ loop statements...}Flowchart: Example: [GFGTABS] C++ #include <iostream> using namespace std; int main() { int i =
2 min read
Java while Loop
Java while loop is a control flow statement used to execute the block of statements repeatedly until the given condition evaluates to false. Once the condition becomes false, the line immediately after the loop in the program is executed. Let's go through a simple example of a Java while loop: [GFGTABS] Java public class WhileLoop { public static v
3 min read
Java Do While Loop
Java do-while loop is an Exit control loop. Unlike for or while loop, a do-while check for the condition after executing the statements of the loop body. Example: [GFGTABS] Java // Java program to show the use of do while loop public class GFG { public static void main(String[] args) { int c = 1; // Using do-while loop do { System.out.println(
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
While loop with Compile time constants
While loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement. It is mostly used in situations where the exact number of iterations beforehand. Below is the image to illustrate the while loop: Syntax: while(test_expression){ // state
6 min read
Retrieving Elements from Collection in Java (For-each, Iterator, ListIterator & EnumerationIterator)
Prerequisite: Collection in Java Following are the 4 ways to retrieve any elements from a collection object: For-each For each loop is meant for traversing items in a collection. // Iterating over collection 'c' using for-each for (Element e: c) System.out.println(e); We read the ‘:’ used in for-each loop as “in”. So loop reads as “for each element
3 min read
Extracting each word from a String using Regex in Java
Given a string, extract words from it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Funny?? are not you? Output : Funny are not you Input : Geeks for geeks?? Output : Geeks for geeks We have discussed a solution for C++ in this post : Program to extract word
2 min read
Get the first letter of each word in a string using regex in Java
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeks Output :Gfg Input : United Kingdom Output : UK Below is the Regular expression to extract the first letter of each word. It uses '/b'(on
1 min read
Check whether two Strings are Anagram of each other using HashMap in Java
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Hashmaps can be used to determine if two given strings are anagrams
3 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Print number of words, vowels and frequency of each character
Given a string str with uppercase, lowercase and special characters. The input string is to end with either a space or a dot. The problem is to calculate the number of words, vowels and frequency of each character of the string in a separate line. Example : Input : How Good GOD Is. Output : Number of words = 4 Number of vowels = 5 Number of upper c
8 min read
Modify a Circular Doubly Linked List such that each node stores the sum of all nodes except itself
Given a circular doubly linked list consisting of N nodes, the task is to modify every node of the given Linked List such that each node contains the sum of all nodes except that node. Examples: Input: 4 ↔ 5 ↔ 6 ↔7 ↔ 8Output: 26 ↔ 25 ↔ 24 ↔ 23 ↔ 22Explanation:1st Node: Sum of all nodes except itself = (5 + 6 + 7 + 8) = 26.2nd Node: Sum of all nodes
15+ min read
Sum of leaf nodes at each horizontal level in a binary tree
Given a Binary Tree, the task is to find the sum of leaf nodes at every level of the given tree. Examples: Input: Output:0063012Explanation:Level 1: No leaf node, so sum = 0Level 2: No leaf node, so sum = 0Level 3: One leaf node: 6, so sum = 6 Level 4: Three leaf nodes: 9, 10, 11, so sum = 30Level 5: One leaf node: 12, so sum = 12 Input: Output:006
14 min read
Generate an Array by multiplying each element of given Array by K
Given an array arr[] of size N and an integer K. The task is to multiply each element of the array by K. Examples : Input: arr[] = { 3, 4 }, K = 2Output: 6 8Explanation: The elements become 3*2 = 6 and 4*2 = 8. Input: arr[] = { 0, 1, 2 }, K = 7Output: { 0, 7, 14 } Approach: The given problem can be solved using the following steps : Iterate through
6 min read
How Eureka Server and Client Communicate with Each Other in Microservices?
Service Discovery is one of the major things of a microservice-based architecture. Eureka is the Netflix Service Discovery Server and Client. The server can be configured and deployed to be highly functional, with each server copying the state of the registered services to the others. In the previous article, we have seen How to Register Microservi
5 min read
Check if two arrays are permutations of each other
Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1}Output: YesInput: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4}Output: NoWe strongly recommend you to minimize your browser and try
15+ min read
Print first letter of each word in a string using regex
Given a string, extract the first letter of each word in it. "Words" are defined as contiguous strings of alphabetic characters i.e. any upper or lower case characters a-z or A-Z. Examples: Input : Geeks for geeksOutput :Gfg Input : United KingdomOutput : UKBelow is the Regular expression to extract the first letter of each word. It uses '/b'(one o
3 min read
Count ways to reach end from start stone with at most K jumps at each step
Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone. Examples: Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -> s
7 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg