[post-views]
In this lesson, you will learn.
foreach loop in Java, also known as the enhanced for loop was introduced in Java 5.Iterable interface) compared to the classic for loop.
The Iterable interface in Java is a part of the Java Collections Framework which includes classes such as
ArrayList, LinkedList, etc.HashSet, LinkedHashSet, TreeSet, etc.PriorityQueue, LinkedList (also a List), etc.
Note: You will learn Java Collection in the upcomming chapters.
for (Type var : collection) {
// Block of statements
}
Iterable interface or an array.
package ch5;
public class ForEachExample1 {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
}
}
Output
1
2
3
4
5
package ch5;
public class ForEachExample2 {
public static void main(String[] args) {
String[] fruits = {"Apple", "Banana", "Cherry",
"Date", "Elderberry"};
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Output
Apple
Banana
Cherry
Date
Elderberry
Use Case
Performance
for loop can lead to slightly cleaner and more readable code when working with collections or arrays
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.