Last updated on February 27th, 2024
In this topic, we will learn about the for-each loop in java. A for-each loop was introduced in Java 1.5. This loop is also known as an enhanced for loop. This loop is used to traverse Collection or Array in java. It helps us avoid programming errors. It makes the code precise and readable. It’s easier to implement. This loop avoids the chance of an infinite loop.
Table of content
1. Syntax of for-each loop
2. How does the for-each loop work?
3. Example of traversing the array elements
4. Example of the sum of array elements
5. Example of traversing the collection elements
6. Conclusion
1. Syntax of for-each loop
The syntax of Java for-each loop is containing a data type with the variable name followed by a colon (:) symbol and then the data source is an array or collection.
for(data_type variable : array){
//body of for-each loop
}
for(data_type variable :collection){
//body of for-each loop
}
2. How does the for-each loop work?
The Java for-each loop is traversing the array or collection until the last element. The for each element, it stores the element in the variable and then executes the body of the for-each loop.
3. Example of traversing the array elements
public class Test{
public static void main(String args[]){
//declaring an array
int arr[]={10,11,12,13,14};
//traversing the array with for-each loop
for(int i:arr){
System.out.println(i);
}
}
}
Output
10
11
12
13
14
4. Example of the sum of array elements
public class Test{
public static void main(String args[]){
int arr[]={10,12,13,14,40};
int total=0;
for(int i:arr){
total=total+i;
}
System.out.println("Total: "+total);
}
}
Output
Total: 89
5. Example of traversing the collection elements
import java.util.ArrayList;
public class Test{
public static void main(String args[]){
//Creating a list of elements
ArrayList<String> list=new ArrayList<String>();
list.add("Peter");
list.add("Robert");
list.add("William");
//traversing the ArrayList of elements using for-each loop
for(String s:list){
System.out.println(s);
}
}
}
Output
Peter
Robert
William
6. Conclusion
In this topic, we learnt about the for-each loop in java and its example.