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:

for(Datatype variable : array | collection){}

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.

public class ForEachLoopEx {

	public static void main(String[] args) {
		String arr[] = new String[4];
		arr[0] = "Name";
		arr[1] = "City";
		arr[2] = "State";
		arr[3] = "Country";
		
		for( String s : arr){
			System.out.println("Array value : "+ s);
		}        
	}
}
Output:
Array value : Name
Array value : City
Array value : State
Array value : Country

For each loop with collection:

public class ForEachLoopEx {

	public static void main(String[] args) {
		ArrayList<String> list = new ArrayList<String>();
		list.add("Name");
		list.add("City");
		list.add("State");
		list.add("Country");
		
		for( String s : list){
			System.out.println("Collection value : "+ s);
		}        
	}
}
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.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

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 […]