For-each loop in java

Let’s learn for-each loop in java.

For-each loop in java

For-each loop traverses each and every element of an array. This loop loops through all the elements sequentially without using index or counter.

For-each loop in optimizes loop and reduces the code. Hence saving time in typing code. It is also called as enhanced for loop.

Also read – create matrix with user input in java

  • Iterating through characters in a string using for-each loop is forward only and in single step.
  • Java for-each is not suitable when you want to modify an array.
  • In enhanced for loop we cannot process another decision making statements (if else statement).
  • As we learnt earlier enhanced for loop cannot obtain index. Hence can’t keep track of index.
  • for-each loop is basically used to iterate elements in Arrays and Collections.

Here’s the syntax and example on java foreach array.

Syntax:

// foreach java
for(<DataType of array><variable name> : <Array to be iterated>)
{
   System.out.println(variable name);
}


Example:
import java.util.*;

class ForEachDemo
{
   public static void main(String[] args) 
   {
      int[] numbers = { 659, 157, 18, 154, 1151 };
      int highestNumber = max(numbers); 
      System.out.println("Highest number is : " + highestNumber);
   }
 
   public static int max(int num[]) 
   {  
      int temp = num[0];  
      // Java foreach 
      for(int a : num)  
      { 
         if(a > temp) 
         { 
            temp = a; 
         }
      }
      return temp; 
   }
}



Output:

for-each loop in java

for each loop java arraylist

Now let’s see java program to traverse over an arraylist using for-each loop.

import java.util.Arrays;
import java.util.List;

public class ForEachLoopArraylist 
{
   public static void main(String[] args) 
   {
      List<Integer> evenNumbers = Arrays.asList(2, 4, 6, 8, 10, 12, 14, 16);
      for(Integer num : evenNumbers)
      {
         System.out.print(num + " ");
      }
   }
}


Output:

2 4 6 8 10 12 14 16

Difference between

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

for loopfor each loop
There is no sequence in execution. Counter can increased as per our wish.Executes in sequence. Counter is increased by one.
was introduced since JDK 1was introduced from JDK 5
no need of implementing interfaceFor containers like array and collection we have 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(a++) and decrement(a–).we can only iterate in incremental order(a++).
best for name-value pairs.best for iterating values. Ex. objects

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

Disadvantages of for each loop in java

  • cannot access particular element of a collection. For example arrayNumbers[6], arraylist.get(2)etc.
  • using for each loop we cannot iterate few elements of a collection or an array.

Enhanced for loop java arraylist

Enhanced for loop should be used with class which implements interface Iterable. For example ArrayList. Here’s java program on enhanced for loop to iterate ArrayList.

import java.util.ArrayList;

public class EnhancedForLoop 
{
   public static void main(String[] args) 
   {
      ArrayList fruits = new ArrayList();
      fruits.add("Pear");    
      fruits.add("Orange"); 
      fruits.add("Grapefruit");  
      fruits.add("Mandarin orange"); 
      fruits.add("Breadfruit"); 
      fruits.add("Banana");
      fruits.add("Avocado");   
      fruits.add("Blueberries");

      for(String str : fruits)
      {
         System.out.println(str);
      }
   }
}


Output:

Pear
Orange
Grapefruit
Mandarin orange
Breadfruit
Banana
Avocado
Blueberries