Java Enhanced For Loop-tutorial
In Java, when you want to iterate over arrays or collections, the traditional for loop requires an index variable. But sometimes you do not care about the index you just want to access every element directly.
To make this easier, Java introduced the Enhanced For Loop (also called the for-each loop). It gives you a shorter, cleaner, and more readable way to loop through elements.
Syntax
To make this easier, Java introduced the Enhanced For Loop (also called the for-each loop). It gives you a shorter, cleaner, and more readable way to loop through elements.
Syntax
for (dataType variable : arrayOrCollection) { // code to be executed}
Explanation:
dataType - Type of elements in the array or collection.
variable - A temporary variable that stores each element one by one.
arrayOrCollection - The array or collection you want to loop through.
Example
Example
public class EnhancedLoopDemo { public static void main(String[ ] args) { int numbers[ ] = {10, 20, 30, 40, 50};
// Using Enhanced For Loop for (int num : numbers) { System.out.println(num); } }}
Output
10
20
30
40
50
Example
public class StringExample { public static void main(String[ ] args) { String names[ ] = {"Alice", "Bob", "Charlie"};
for (String name : names) { System.out.println("Hello, " + name); } }}
Output
Hello, Alice
Hello, Bob
Hello, Charlie
Key Point
- works with arrays and collections (like ArrayList, HashSet, etc.).
- Easier and cleaner than traditional for loop.
- You cannot directly modify the array/collection inside the loop.
- Best for reading data rather than updating it.
Advantage
Less code, more readability.
Avoids index related mistakes.
Makes iteration simple for beginners.
Limitations
No access to index values.
Cannot remove elements while iterating (use Iterator instead).
Mostly useful when you only need to read elements.
Real Life Use Case
Imagine you have a list of students names, and you just want to greet each student. Instead of writing extra index logic, a for-each loop gives a direct, clean way.
Two Minute Drill
- Enhanced For Loop also called as For-Each Loop.
- Best for reading elements in arrays/collections.
- No index available, no direct modification.
- Cleaner and shorter than traditional for