for each loop in java

In the previous post, we have seen the working of for loop. In this post, we will learn about for each loop.

This loop has been added in java 5, also known as enhanced for loop. It is mostly used for traversing over an array or collection. It is more convenient and concise that reads the element one by one in order.

We don’t have to use any counter like for loop to increment or decrements variable value. That is internally taken care by for each loop.

Syntax of for each loop:

It improves the readability of the code.

Let’s take an example of for each loop.

For each loop with array:

There is an string array whose values are printed using for each loop.

Output:
Array value : Name
Array value : City
Array value : State
Array value : Country

For each loop with collection:

Output:
Collection value : Name
Collection value : City
Collection value : State
Collection value : Country
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
for loop in java
if statement in java
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. He is an automation engineer having more than 8 years of experience who loves troubleshooting in automation and finding innovative ways to solve the problems. His other leisurely activities includes playing harmonica, paintings, sketching portrait, watching movies and travelling etc.

You may also like...

1 Response

  1. August 10, 2015

    […] the previous post, we have seen the working of for each loop in java. In this post, we will look at if statement […]

Leave a Reply

Your email address will not be published. Required fields are marked *