The for-each loop is used to traverse the array or collection in java. It is easier to use than simple for loop because we don’t need to increment value and use subscript notation. It works on the basis of an element, not an index. It returns elements one by one in the defined variable.
Syntax of Java for-each Loop:
for (Type var : array) { //code to be executed }
Example 1: Printing Array using for-each loop.
public class For_each_loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
String [] subjects = {"computer","maths","chemistry","physics"};
for(String x : subjects) {
System.out.println(x);
}
}
}
Example 2: Printing ArrayList using for-each loop
import java.util.ArrayList;
public class For_each_loop {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> subjects = new ArrayList<String>();
subjects.add("computer");
subjects.add("maths");
subjects.add("chemistry");
subjects.add("physics");
for(String x : subjects) {
System.out.println(x);
}
}
}
Comments (No)