Logo

Unleash the Power of the For-Each Loop in Java: A Simple Guide

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!

See all content
Top Picks

Subscribe now and never miss an update!

Subscribe to receive weekly news and the latest tech trends

Logo
1 345 657 876
nerdy-mind 2025. All rights reserved