For-Each Loop in Java - GeeksforGeeks
For-Each Loop in Java - GeeksforGeeks
Java Arrays Java Strings Java OOPs Java Collection Java 8 Tutorial Java Multithreading Java Exceptio
Syntax:
https://www.geeksforgeeks.org/for-each-loop-in-java/ 1/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
Java
import java.io.*;
class Easy
// array declaration
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
Java
return maxSoFar;
}
}
Output
1. For-each loops are not appropriate when you want to modify the array:
https://www.geeksforgeeks.org/for-each-loop-in-java/ 4/10
4/22/24, 8:28 PM For-each loop in Java - GeeksforGeeks
Java
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--] :: " +
}
}
Output
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
https://www.geeksforgeeks.org/for-each-loop-in-java/ 6/10