Iteration Methods
Traditional For Loop
The most classic method for array iteration in Java.
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Enhanced For Loop (For-Each)
A more concise and readable approach for simple iterations.
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
While Loop Iteration
Provides more control over iteration conditions.
int[] numbers = {1, 2, 3, 4, 5};
int index = 0;
while (index < numbers.length) {
System.out.println(numbers[index]);
index++;
}
Java 8 Stream API
Modern approach with functional programming capabilities.
int[] numbers = {1, 2, 3, 4, 5};
Arrays.stream(numbers).forEach(System.out::println);
Method |
Performance |
Readability |
Flexibility |
Traditional For |
Fastest |
Medium |
High |
Enhanced For |
Good |
High |
Low |
While Loop |
Moderate |
Medium |
High |
Stream API |
Slowest |
High |
Very High |
Iteration Flow Visualization
graph TD
A[Start Array Iteration] --> B{Choose Iteration Method}
B --> |Traditional For| C[Index-based Iteration]
B --> |Enhanced For| D[Direct Element Access]
B --> |While Loop| E[Conditional Iteration]
B --> |Stream API| F[Functional Iteration]
Best Practices
- Use traditional for loop for performance-critical code
- Prefer enhanced for loop for simple iterations
- Leverage Stream API for complex transformations
- Consider memory and performance implications
LabEx recommends mastering multiple iteration techniques to write efficient Java code.