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:

  • Declaration starts with the keyword for like a normal for-loop.
  • Instead of initializing a loop counter variable, declare a variable that is of the same type as the base type of the array, followed by a colon, which is then followed by the array name in Java.
  • In the body of the loop, you can use the loop variable you created rather than using an indexed array element.
  • It’s commonly used to iterate over an array or a Collections class.

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.