For-Each in Java


A second form implements a "for-each" style loop. As you may know, contemporary languages theory has embraced the for-each concepts, and it has become a standard feature that programmers have come to expect. The loop for each style is designed to create cycles for collecting items like arrays.The For-Each loop can be used to output but not as input. Here is the general form of the traditional for-each statement :

for(type itr-var : collection)
{
  //body of code
}

For-Each Loop Example 1

The following example contains many strings in a collection or array of strings. Each string is printed with a for-each loop.

Program
public class Main
{
	public static void main(String[] args) 
	{
	   String arr[]={"India","Pakistan","Bangladesh","Sri Lanka"};
	   for(String items : arr)
	   {
	       System.out.println(items);
	   }
	}
}
Run

For-Each Loop Example 2

In the following example, we have calculated the sum of the first seven numbers of the integer collection using the for-each loop.

Program
public class Main
{
	public static void main(String[] args) 
	{
	    int s=0;
	   int nums[]={1,2,3,4,5,6,7,8,9};
	   for(int x : nums)
	   {
	       System.out.println("Value is :"+x);
	       s+=x;
	       if(x==7)
	       {
	           break;
	       }
	   }
	   System.out.println("Summetion of first 7 elements : "+s);
	}
}
Run