for-each loop in java

Let’s learn for-each loop in java.

for-each loop in java

for-each in java traverse each element of an array sequentially without using index or counter. for-each in java or enhanced for loop was introduced in JDK 1.5

Here’s the syntax and example on for each loop.

Syntax:

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


example of for each loop in java

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

NOTE:

  • Iterating through characters in a string using for-each loop is forward only and in single step.
  • for-each loop 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 can’t keep track of index.
  • for-each loop is basically used to traverse elements in Arrays and Collections.

Disadvantage of for each 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.

Traversing or iterating array using for each in java

Let’s iterate array using for each in java.

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


Also read – ArrayList in java