for each loop in Java

for each loop is also known as enhanced for loop. for each loop in Java introduced in the 1.5 version. It is specially designed to retrieve elements of arrays and collections.

for each loop in Java

for each loop syntax

for (dataType variable name: array/collection){
           operations with variable name;
}

Java program to print 1-D Array

For Each LoopNormal For Loop
public class ForEach {
public static void main(String[] args) {
int [] array = {5,10,15,20,25};
for(int arrayElement:array){
System.out.println(arrayElement);
}
}
}
public class For {
public static void main(String[] args) {
int [] array = {5,10,15,20,25};
for(int i=0; i<array.length;i++){
System.out.println(array[i]);
}
}
}

Java program to print 2-D Array

for each loopfor loop
public class ForEach {
public static void main(String[] args) {
int [][] array = {{5,10,15,20,25}, {30,35,40,45,50}};
for(int[] arrayElement:array){
for(int item : arrayElement){
System.out.println(item);
}
}
}
}
public class For {
public static void main(String[] args) {
int [][] array = {{5,10,15,20,25}, {30,35,40,45,50}};
for(int i=0; i<array.length;i++){
for(int j=0; j<array[i].length;j++){
System.out.println(array[i][j]);
}
}
}}

for each loop Properties

  • For each loop is the best choice to retrieve elements of arrays and collections.
  • for each loop is only applicable to arrays and collections.
  • By using normal for loop we can print array elements either in the original order or in reverse order, but by using for each loop we can print array elements only in the original order.

for each loop example in Java

public class ForEach {
    public static void main(String[] args) {
       String [] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
        for(String month:months){
            System.out.print(month + " ");
            }
        }
    }

for each loop example in Java

Similar Java Tutorials

Leave a Comment