For-each loop in java

Let’s learn for-each loop in java.

For each loop java

For each loop java or new version of “for” loop is used with arrays and loops through all the elements without using index or counter.

For-each loop in java optimizes loop and reduces the code. Hence saving time in typing code.

Also read – comments in java

The data type declared in java foreach must match datatype of the array or list that we are iterating.

Syntax:

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


Example:
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

NOTE

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