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); } } }
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); } } }
Collection value : Name
Collection value : City
Collection value : State
Collection value : Country
1 Response
[…] the previous post, we have seen the working of for each loop in java. In this post, we will look at if statement […]