For-each loop in java

Let’s learn for-each loop in java.

For-each loop in java

For-each loop traverse each element of an array sequentially without using index or counter.

For-each loop is nothing but enhanced for loop.

For-each loop or enhanced for loop was introduced in JDK 1.5

NOTE:

  • Iterating through characters in a string using for-each loop is forward only and in single step.
  • for-each loop in java is not suitable when you want to modify an array.
  • In for-each loop we cannot process two decision making statements at one time like if else statement.
  • for-each loop in java can’t keep track of index.
  • for-each loop in java is basically used to traverse elements in Arrays and Collections.

Here’s the syntax and example of for each loop in java.

Syntax:

for(<DataType of array><variablename> : <Array to be iterated>)
{
   // code
}


Example:

import java.util.*;
public class ForEachLoopExample
{
   public static void main(String[] args)
   {
      int[] numbers = {2, 4, 6, 8, 10};
      // for each loop
      for(int n : numbers)
      {
         System.out.println(n);
      }
   }
}


Output:

2
4
6
8
10


Difference between for and for each loop

Here’s the difference between for and for each loop in java.

for loopfor each loop
There is no sequence in execution. Here in for loop we can change counter as per our wish.Executes in sequence. Counter is increased by one.
was introduced from start, JDK 1.was introduced from JDK 5 onwards.
no need of implementing interface.To loop over containers using for each loop, container should implement Iterable interface.
can have access to index. Hence can replace element in an array.can’t replace element at given index since there is no access to array index.
counter can increment and decrement.we can only iterate in incremental order cannot decrement.

Here’s the java program on difference between for and for each loop in java.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class DifferenceBetween 
{
   public static void main(String[] args) 
   {
      List<String> players = new ArrayList<>(Arrays.asList("Virat", "Rohit", "Dhoni"));
      // iterate over List using for loop
      System.out.println("using for loop in java: ");
      for(int a = 0; a < players.size(); a++) 
      {
         System.out.println(players.get(a));
      }
      // iterate over List using enhanced for loop
      System.out.println("using for each loop in java: ");
      for(String str : players)
      {
         System.out.println(str);
      }
   }
}


Output:

using for loop in java:
Virat
Rohit
Dhoni
using for each loop in java:
Virat
Rohit
Dhoni


for-each loop in java: Disadvantage of for each loop in java

Here is disadvantage of for each loop in java.

  • can’t use for each loop to remove elements while traversing collections.
  • can’t use for each loop to modify given index in an array.
  • can’t use for each loop to iterate over different arrays.

java foreach array

Let’s iterate array using for-each loop.

public class ForEachArrayExample
{
   public static void main(String[] args)
   {
      String[] strColors = {"red", "blue", "green", "orange", "violet"};
      // using for loop
      System.out.println("Using conventional for loop: ");
      for(int a = 0; a < strColors.length; a++)
      {
         System.out.println(strColors[a]);
      }
      System.out.println("\nUsing foreach loop: ");
      // using for-each loop
      for(String str : strColors)
      {
         System.out.println(str);
      }
   }
}


Output:

Using conventional for loop:
red
blue
green
orange
violet

Using foreach loop:
red
blue
green
orange
violet


enhanced for loop java arraylist

For each loop or enhanced for loop can looped with any class which implements Iterable interface like ArrayList.

Let’s see an example on enhanced for loop java arraylist.

import java.util.ArrayList;
public class EnhancedForLoopArrayList
{
   public static void main(String[] args)
   {
      ArrayList<String> al = new ArrayList<String>();
      al.add("red");
      al.add("yellow");
      al.add("green");
      al.add("white");
      for(String str : al)
         System.out.println(str);
   }
}


Output:

red
yellow
green
white