☕ Java for-each Loop – Enhanced Loop Simplified
The for-each loop (also called the enhanced for loop) in Java is a powerful repetition control structure that makes iterating over arrays and collections simple and readable.
It is especially useful when:
✔ You need to execute a loop a specific number of times
✔ You want to iterate without using an index
✔ You don’t know the exact number of iterations
🔹 Syntax of for-each Loop
for (declaration : expression) {
// Statements
}
Execution Process:
Declaration → A variable compatible with the array element type
Expression → The array or collection being iterated
The declared variable holds the current element during each iteration.
🔹 Example 1: Iterating Over a List of Integers
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
for (Integer x : numbers) {
System.out.print(x);
System.out.print(",");
}
📌 Output:
10, 20, 30, 40, 50,
🔹 Example 2: Iterating Over a List of Strings
List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy");
for (String name : names) {
System.out.print(name);
System.out.print(",");
}
📌 Output:
James, Larry, Tom, Lacy,
🔹 Example 3: Iterating Over an Array of Objects
Student[] students = {
new Student(1, "Julie"),
new Student(3, "Adam"),
new Student(2, "Robert")
};
for (Student student : students) {
System.out.print(student);
System.out.print(",");
}
This demonstrates how the enhanced for loop works seamlessly with custom objects as well.
💡 The for-each loop improves readability, reduces boilerplate code, and minimizes errors related to index handling.
Mastering looping concepts is essential for writing clean and efficient Java programs.
#Java #ForEachLoop #EnhancedForLoop #JavaProgramming #Collections #Arrays #Coding #FullStackJava #Developers #AshokIT
Next time I prompt an LLM to generate Java code, I’ll add: ‘please use var ’ 😀 Great read!