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.
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.
for (type var : array | collection)
{
//statements using var;
}
// 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.