Tired of clunky index-based loops in Java? Enter the for-each loop (also known as the enhanced for loop), a cleaner and more readable way to iterate through arrays and collections!
Instead of wrestling with indices, the for-each loop directly accesses each element in the sequence. The syntax is straightforward:
```java
for (DataType element : collection) {
// Code to be executed for each element
}
```
`DataType` represents the type of element within your `collection` (like an array or an ArrayList). `element` is a variable that holds the current element during each iteration. The `collection` is the array or collection you're iterating over.
For example, to print all numbers in an array:
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
```
The for-each loop shines in its simplicity, making your code easier to understand and maintain. While it might not be suitable for situations requiring index manipulation (like modifying the collection while iterating), it's a fantastic choice for read-only traversals!