Yes, Java provides a shorter way to write a for
loop using the enhanced for-each
loop, ideal for iterating over arrays or collections. Instead of managing indexes, it directly accesses each element:
Example:
java
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
Here, number
represents each element in the array numbers
.
For collections like ArrayList
:
java
List<String> names = List.of("Alice", "Bob", "Charlie");
for (String name : names) {
System.out.println(name);
}
The enhanced for
loop improves readability and reduces boilerplate compared to traditional for
loops.