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 syntax
for (dataType variable name: array/collection){
operations with variable name;
}
Java program to print 1-D Array
For Each Loop | Normal 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 loop | for 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 + " ");
}
}
}
Similar Java Tutorials
- Odd Even in Java
- Fibonacci Series Java
- Prime Number Java
- Literals in Java
- Variables in Java
- Command Line Arguments in Java
- Java Coding Standards
- Var-Args Method in Java
- new operator in Java
- Conditional operator in Java
- Assignment operator in Java
- Command line argument in Java
- Java coding standards
- Control Flow Statements in Java
- If – else in Java
- Switch statements in Java
- For loop in Java
- While loop in Java
- Do while loop in Java