dsa

Java for-each Loop(Enhanced for Loop)

In this tutorial, we will learn how to use for-each loop in Java with the help of examples and we will also learn about the working of this Loop in computer programming.

  • Introduction

    The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements. The advantage of the for-each loop is that it eliminates the possibility of bugs and makes the code more readable. It is known as the for-each loop because it traverses each element one by one.

  • Advantages :

    • It makes the code more readable.
    • It eliminates the possibility of programming errors.
  • Syntax :

    
    for (type var : array | collection) 
    { 
        //statements using var;
    }
  • Example :

    
    // Java program to illustrate 
    // for-each loop 
    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 max = numbers[0]; 
    		
    		// for each loop 
    		for (int num : numbers) 
    		{ 
    			if (num > max) 
    			{ 
    				max = num; 
    			} 
    		} 
    	return max; 
    	} 
    } 
      

    Output :

    
    The highest score is 132.