For-each loop in java

In this post we are going to learn for-each loop in java.

For-each loop in java

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

Foreach 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 foreach loop must match datatype of the array or list that we are iterating.

Syntax:

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];  
      // for-each loop 
      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.
  • Foreach loop 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 Collection class or arrays or ArrayList.