4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exceptio
For-each loop in Java
Last Updated : 16 Feb, 2023
Prerequisite: Decision making in Java
For-each is another array traversing technique like for loop, while loop, do-
while loop introduced in Java5.
It starts with the keyword for like a normal for-loop.
Instead of declaring and initializing a loop counter variable, you 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, you can use the loop variable you created rather than
using an indexed array element.
It’s commonly used to iterate over an array or a Collections class (eg,
ArrayList)
Syntax:
for (type var : array)
{
statements using var;
}
https://www.geeksforgeeks.org/for-each-loop-in-java/ 1/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
Simple program with for each loop:
Java
/*package whatever //do not write package name here */
import java.io.*;
class Easy
public static void main(String[] args)
// array declaration
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar)
System.out.print(element + " ");
}
}
Output
https://www.geeksforgeeks.org/for-each-loop-in-java/ 2/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
10 50 60 80 90
The above syntax is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
Java
// Java program to illustrate
// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
https://www.geeksforgeeks.org/for-each-loop-in-java/ 3/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
return maxSoFar;
}
}
Output
The highest score is 132
Limitations of for-each loop
decision-making
1. For-each loops are not appropriate when you want to modify the array:
for (int num : marks)
{
// only changes num, not the array element
num = num*2;
}
2. For-each loops do not keep track of index. So we can not obtain
array index using For-Each loop
for (int num : numbers)
{
if (num == target)
{
return ???; // do not know the index of num
}
}
3. For-each only iterates forward over the array in single steps
// cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}
https://www.geeksforgeeks.org/for-each-loop-in-java/ 4/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
4. For-each cannot process two decision making statements at once
// cannot be easily converted to a for-each loop
for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}
5. For-each also has some performance overhead over simple
iteration:
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime = Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " + (endTime - startTime) + " ms")
// Type 2
startTime = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: " + (endTime - startTime
// Type 3
startTime = Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
https://www.geeksforgeeks.org/for-each-loop-in-java/ 5/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating collection.size() first :: " + (endT
// Type 4
startTime = Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime = Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j > size ; j--] :: " +
}
}
// This code is contributed by Ayush Choudhary @gfg(code_ayush)
Output
For each loop :: 45 ms
Using collection.size() :: 11 ms
By calculating collection.size() first :: 13 ms
Using [int j = list.size(); j > size ; j--] :: 15 ms
Related Articles:
For-each in C++ vs Java
Iterator vs For-each in Java
Feeling lost in the vast world of Backend Development? It's time for a
change! Join our Java Backend Development - Live Course and embark on an
exciting journey to master backend development efficiently and on schedule.
What We Offer:
Comprehensive Course
Expert Guidance for Efficient Learning
Hands-on Experience with Real-world Projects
Proven Track Record with 100,000+ Successful Geeks
235 Suggest improvement
https://www.geeksforgeeks.org/for-each-loop-in-java/ 6/10