What is for-each loop in Java?

Last updated on Nov 27,2019 4K Views

What is for-each loop in Java?

edureka.co

The for-each loop in Java is generally used for iteration through the array elements in different programming languages. Java 5 introduced this for-each loop, which is also called as an enhanced for-each loop. So, in this article, I’ll help you guys get a proper gist about how for-each loop in Java works.

I’ll be discussing the below topics:

Importance of for-each loop

Using a for-each loop, you can traverse a given array. It starts with the keyword for followed by the condition.

This for statement is a very commonly used looping statement. It includes initialization of an expression that specifies an initial value for an index, and the following condition expression determines whether the loop is continued or not and the last iteration expression allows the index to be modified at the end of each pass. It is known as the for-each loop because it traverses each element one by one. 

Also, it is recommended to use the for-each loop in Java for traversing the elements in the array and collection because it makes the code readable really good.

Now let’s take a look at the syntax of this for-each loop.

Syntax:

for(initialization; condition; iteration){
//body of for-each loop
}

Explanation:

Now let’s move ahead and take a look at an example.

Example

 class example
{
public static void main(String[] args)
{
int i;
for(i = 1;i<=3; i++)
{
System.out.println("value of i = " +i);
}
} 

Output:

value of i = 1
value of i = 2
value of i = 3

This brings us to the end of this article where we have learned about the for-each loop in Java. Hope you are clear with all that has been shared with you in this tutorial.

If you found this article on “for-each loop in Java” relevant, check out the Edureka Java Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. 

We are here to help you with every step on your journey, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

If you come across any questions, feel free to ask all your questions in the comments section of “For-each loop in Java” and our team will be glad to answer.

Upcoming Batches For Java Certification Training Course
Course NameDateDetails
Java Certification Training Course

Class Starts on 11th May,2024

11th May

SAT&SUN (Weekend Batch)
View Details
Java Certification Training Course

Class Starts on 1st June,2024

1st June

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR UiPath Selectors Tutorial