For Each Loop in Java | Enhanced For Loop

The for each loop in Java (also referred to as enhanced for loop) is an extended feature of Java language that was introduced with the J2SE 5.0 release.

This feature is specially designed to retrieve elements of the array efficiently rather than using array indexes.

Java for-each loop can also be used to retrieve elements of a collection. A collection represents a group of elements like Integer values, strings, or objects.

Enhanced for loop repeatedly executes a group of statements for each element of the collection. It can execute as many times as a number of elements in the collection.

Syntax of Java For each loop


The general syntax for for-each loop in Java is as follows:

for(Type Identifier : Expression)
{
   // statements;
}

Here, Type represents the data type or object used; Identifier specifies the name of an iteration variable that receives elements from a collection, one at a time, from beginning to end; and an Expression is an object of java.lang.Iterable interface or an array.

Note: Unlike some other programming languages, such as C#, that implement a for-each loop by using foreach keyword.

But Java language added the for-each capability by enhancing the for statement. The advantage of enhancing is that no new keyword is needed, and no preexisting code is broken.

Therefore, the for-each loop is also known as enhanced for loop in Java. Professional programmers generally use enhanced for loop in the industry.

Let’s understand the above syntax with the help of an example. Consider the following statements below:

int numarr[3] = {10, 20, 30};
for(int i = 0, i <= 3; i++)
{
  if(numarr[i] >  5 && numarr[i] < 40)
    System.out.println("Selected value: " +numarr[i]);
}
This code is equivalent to the following code:
int numarr[3] = {10, 20, 30};
for(int i : numarr)
{
  if(i > 5 && i < 40)
    System.out.println("Selected value: " +i);
}

Thus, for each loop in Java can be used to track elements of an array efficiently.


In the same style, for each loop can also be used to track elements of the collection, as follows:

ArrayList<String> cities = new ArrayList<String>();
  cities.add("Delhi");
  cities.add("Mumbai");
  cities.add("Dhanbad");
  cities.add("Kolkata");
// Iterating arraylist using enhanced for loop.
  for(String city : cities)
  {
    System.out.println("City name: " +city);
  }

 Example Program based on for-each loop


1. Let’s take an example program where we retrieve elements of an array one by one using for-each loop and display it on the console.

Program source code 1:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
// Declare an array with 5 elements.
     String cities[] = {"Dhanbad", "Mumbai", "Delhi", "New York", "Tinpahar" };	
  
// Using for each loop to retrieve elements (cities) from an array.
    System.out.println("Name of cities:");
    for(String city : cities)
    {  
      System.out.println(city); // city represents each element of an array.
   }
 }}
Output:
             Name of cities:
             Dhanbad
             Mumbai
             Delhi
             New York
             Tinpahar

2. Let’s take another example program where we will calculate the sum of the first 10 numbers using enhanced for loop and display it on the console.

Program source code 2:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
// Declare an array with 10 elements.
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = 0;
	
// Iterating elements using for-each loop to display and sum the values.
    for(int x : nums) {
         sum += x;
     }
   System.out.println("Sum: " + sum);
 }	
}
Output:
             Sum: 55

3. Suppose in the above program, we want to calculate only the sum of five numbers out of 10 numbers. Here, we will use break statement. Let’s write the code for it.

Program source code 3:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
// Declare an array with 10 elements.
     int nums[ ] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     int sum = 0;
	
// Iterating elements using for-each loop to display and sum the values.
    for(int x : nums) {
       sum += x;
      if(x == 5) break; // stop the loop when x is equal to 5.
     }
   System.out.println("Sum of first 5 elements: " + sum);
 }	
}
Output:
             Sum of first 5 elements: 15

As you can observe in the program, the for-each loop stops after the fifth element has been obtained.

Iterating elements of Multidimensional Array


The enhanced for loop can also be used on multidimensional arrays. In Java, multidimensional arrays consist of arrays of arrays. Let’s understand the code with the help of an example program. Look at the source code.

Program source code 4:

package javaProgram;
public class Test {
public static void main(String[] args) 
{
int sum = 1;
int nums[ ][ ] = new int[3][5];
for(int i = 1; i < 3; i++)
{
 for(int j = 1; j < 5; j++)
 {	 
  nums[i][j] = i * j;
		
// Using for-each for to display and sum the values.
 for(int x[ ] : nums) 
 {
  for(int y : x) 
  {
    sum += y;
   }
  }
 }
}	
System.out.println("Sum: " + sum);
}}
Output:
             Sum: 101

5. Let’s take one more example where we will search an element from an array. If the element is found, it will stop. Look at the source code to understand better.

Program source code 5:

package javaProgram;
public class SearchTest {
public static void main(String[] args) 
{
int nums[] = { 1, 8, 3, 7, 5, 6, 10, 4 };
int val = 10;
boolean found = false;
	
// Searching element value 10 from an array using for each loop.
    for(int x : nums) {
      if(x == val) {
       found = true;
       break;
      }
    }
if(found)
  System.out.println("Value found!");
 }
}
Output:
             Value found!

Hope that this tutorial has covered almost all the important points related to for each loop in Java with example programs. I hope that you will have understood and practice programs.
Thanks for reading!!!
Next ⇒ Switch statement in Java

⇐ Prev Next ⇒