Thursday, January 16, 2025
HomeProgrammingIs there a shorter way to write a for loop in Java?

Is there a shorter way to write a for loop in Java?

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.

See also  List of remotes for a Git repository?
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x