Java for-each loop

Java for-each loop

  • The for-each loop was introduced in the Java 5 version.
  • The java for-each loop is also known as the enhanced loop.
  • The for-each loop is one of the ways of traversing an array or collection just like for loops, while loops,do-while loops.

Syntax:

 for(data_type variable : array | collection){  
    //body of for-each loop  
    } 
  • It is often good to traverse the elements of array & collections as it reduces many programming errors.
  • The for-each loop is not a general-purpose as it is specific only for arrays & collections.

Example 1: Printing array elements

Java Code

class Solution {
  public static void main(String[] args) {
 	 
	// create an array
	int[] numbers = {3, 9, 5, -5};
    
	// for each loop
	for (int number: numbers) { // Auto increament
  	System.out.print(number+" ");
	}
  }

Output: 3 9 5 -5

Example 2: Printing array elements using For loop

Java Code

class  Solution{

public static void main(String[] args){

  int[] numbers = {3,9,5,-5};

  for(int i = 0 ; i<numbers.length ; i++){
  System.out.print(numbers[i]+" ");
   }
  }
}

Output: 3 9 5 -5

Explanation:

  • We can observe that we are printing the array using for-each and for loop where the for-each loop is easy to code and with fewer programmatic errors than for loop.
  • The elements in the for-each loop are traversed and incremented automatically by one whereas in the for loop we can define our own increment value.
  • In the for loop, we are printing the array elements using the index value defined in the for loop whereas in the for-each loop we don’t require any index value to move forward for other elements

Example: Max So Far

Java Code

class For_Each {
  public static void main(String[] arg) {

    int[] marks = {125, 132, 95, 116, 110 };
    
    int highest_marks = maximum(marks);
    System.out.println("The highest score is " + highest_marks);

  }

  public static int maximum(int[] numbers) {
    int maxSoFar = numbers[0];

    // for each loop
    for (int num: numbers) {
      if (num > maxSoFar) {
        maxSoFar = num;
      }
    }
    return maxSoFar;
  }
}

Output: The highest score is 132

Explanation:

  • In the above code, we are finding out the maximum element in the array numbers.
  • We are initializing the maxSoFar element with the first number of the array numbers.
  • Using for-each loop we are moving forward the array numbers and checking whether any other number greater than the maxSoFar.
  • If any element is greater than the maxSoFar, store it in the maxSoFar and return.

When to use a for-each loop?

  • Only use the for-each loop when you want to loop through all the values in an array or list.
  • In the for-each loop, we can only traverse in the forwarding direction only whereas in the for loop we can traverse the array in both forward and backward directions.

When not to use a for-each loop?

  • If you only want to loop through part of an array or list use a for loop instead. 
  • Use a for loop instead of a for-each loop if you want to change any of the values in the array or list.

Limitations of the for-each loop:

  • for-each loop is not appropriate when you want to modify the array.

Example:  

for(int num : marks)
{
num = num * 2; // Only changes num, not the array element.
}
  • The for-each loop does not keep track of the index, so we cannot obtain the array index of the for-each loop

Example:

 for (int num : numbers) 
{
   if (num == target) 
{
   return ???;   // do not know the index of num
}
}
  • The for-each loop can only traverse in the forwarding direction. 

Example:

 // cannot be converted to a for-each loop
for (int i=numbers.length-1; i>0; i--)
{
  	System.out.println(numbers[i]);
}

Special thanks to Abbas Hussain Muzammil for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article