๐ Java Enhanced For Loop (For-Each Loop) – Simple Guide with Examples
The enhanced for loop (also called the for-each loop) in Java provides a concise way to iterate over arrays and collections. It improves readability and reduces the chances of errors like index-out-of-bounds.
In this article, you'll learn how to use it, when to use it, and see clear examples that show how it compares to traditional for
loops.
๐ What Is the Enhanced For Loop in Java?
Introduced in Java 5, the enhanced for loop is used to iterate through elements of an array or collection without using an index.
๐ Syntax:
for (dataType variable : arrayOrCollection) {
// code block
}
-
dataType
: The type of elements in the array/collection -
variable
: A temporary variable holding each element -
arrayOrCollection
: The data structure being iterated over
๐งช Example 1: For-Each Loop with Arrays
public class ForEachExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
}
}
✅ Output:
10
20
30
40
This is much cleaner than:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
๐งช Example 2: For-Each Loop with ArrayList
import java.util.ArrayList;
public class ForEachList {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
⚠️ Limitations of Enhanced For Loop
While it's great for reading data, the for-each loop has a few limitations:
Limitation | Details |
---|---|
No index access | You can't get the current index directly |
No element modification | You can't replace elements in arrays directly |
One-directional iteration | Can't iterate backward |
Not suitable for removal | Use iterator when modifying collections |
๐ก When Should You Use For-Each?
Use the enhanced for loop when:
-
You need to read elements, not modify them
-
Index value isn't important
-
You want cleaner and safer code
Avoid it when:
-
You need the index
-
You're modifying the list during iteration (e.g., removing elements)
๐ Quick Comparison
Feature | Traditional For Loop | Enhanced For Loop |
---|---|---|
Index control | ✅ Yes | ❌ No |
Cleaner syntax | ❌ Verbose | ✅ Cleaner |
Modifying elements | ✅ Possible | ❌ Not allowed directly |
Reverse iteration | ✅ Possible | ❌ Not supported |
๐ Summary
The for-each loop in Java simplifies the process of iterating over arrays and collections. It's ideal for most read-only operations and enhances code readability. While it has some limitations, it's a great tool in most everyday use cases.
Would you like to watch video explanation with code demo for this article? watch video below:
No comments:
Post a Comment