Java > Core Java > Control Flow > Enhanced for-loop (for-each)
Enhanced For-Loop (For-Each) Example: Summing Elements in an Integer Array
This example demonstrates using the enhanced for-loop to calculate the sum of elements in an integer array. This showcases a simple yet common use case where the for-each loop simplifies code and improves readability.
Calculating Sum with For-Each Loop
In this code, the for-each loop iterates through each integer element in the numbers
array. For each iteration, the current element is assigned to the number
variable. The value of number
is then added to the sum
variable. After the loop completes, the sum
variable contains the total sum of all the elements in the array.
public class ForEachSum {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
// Enhanced for-loop to calculate the sum of the 'numbers' array
for (int number : numbers) {
sum += number;
}
System.out.println("Sum: " + sum);
}
}
Concepts Behind the Snippet
The key concept here is the simplification of array traversal. Instead of needing to manage an index variable and access the array elements using that index, the for-each loop automatically handles the iteration process, allowing you to focus solely on processing the elements themselves. This reduces the risk of errors related to index management.
Real-Life Use Case
Imagine calculating the total score of a student based on individual subject scores stored in an array. You can use a for-each loop to easily iterate through the subject scores and sum them up to get the total score, making the code cleaner and more maintainable.
Best Practices
Interview Tip
When discussing for-each loops in an interview, emphasize their role in simplifying code and improving readability, especially when working with collections or arrays. Also, be prepared to discuss its limitations, such as not being able to access the element's index directly and the potential issues when modifying the collection during iteration.
When to Use Them
Use for-each loops primarily when you need to iterate through all elements of a collection or array and perform a simple operation on each element, such as calculating the sum, finding the maximum/minimum, or printing the values. It is ideal when you only need to read the elements and do not need to modify the underlying collection.
Memory Footprint
The memory footprint is similar to a traditional for loop in this scenario. The for-each loop doesn't create significant additional overhead. The memory used is primarily for the sum
variable and the temporary variable used to store the current element being processed.
Alternatives
A traditional for loop could be used, but it would require explicit index management. Java 8 streams also offer a concise alternative using the sum
operation: Arrays.stream(numbers).sum()
. This approach leverages functional programming and can be even more readable for simple aggregations.
Pros
Cons
FAQ
-
Can I use the for-each loop to iterate in reverse order?
No, the enhanced for-loop iterates in a forward direction only. To iterate in reverse order, you would need to use a traditional for loop with a decrementing index. -
What happens if the array is empty?
If the array is empty, the for-each loop will simply not execute. The code within the loop will not be run at all, and the program will continue to the next statement after the loop.