Java for each loop

Its also known as the enhanced for loop .

It is used to majorly iterate arrays and collections like ArrayList.

The syntax:

for(variable_type variable_name:array or collection to iterate){

//loop body

}

1.The variable type and variable name(declaration)-in this section we declare a variable that will be assigned/hold value for the current element in each iteration of the array,i.e. in each iteration the variable will be assigned a different value akin to array[i] in the the for loop.The type is the same as the type of elements in the array.

2.array or collection to iterate-the array or collection to iterate

 

Example

package devsought.forloop;

 

public class ForEachLoopExample1 {

 

    public static void main(String... args) {

        int[] scores = new int[]{75, 55, 67, 88, 52};

        double total = 0;

        for (int score : scores) {

            total += score;

        }

        System.out.println("Total score=>" + total);

        System.out.println("Average score=>" + (total / scores.length));

    }

}

Output:

Explanation:

In each iteration we add the score to the total.At the end we print the total score and the average

Advantage of the enhanced for loop/for each loop over the traditional for loop

Its easier to write and understand compared to the for loop which in which more code is written.

The program in this tutorial are available on Github.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.