The for-each loop, sometimes called the improved for loop in Java, offers a condensed method of iterating over elements in an array or any Iterable (like collections) without requiring explicit index management.
Syntax :
for (data_type item : array_or_collection) {
// statements
}
array_or_collection: an array or java collection
item: each item of array or collection is assigned to this variable
data_type: the data type of the array or collection
Example 1:
/*** Java foreach Example*/public class JavaExample {public static void main(String[] args) {int[] numberArray = {1, 2, 3, 4, 5};for (int numberVal : numberArray) {System.out.println("Element Of array: " + numberVal);}}}
Output:
Element Of array: 1 Element Of array: 2 Element Of array: 3 Element Of array: 4 Element Of array: 5
Example 2:
import java.util.ArrayList;import java.util.List;/*** Java foreach Example*/public class JavaExample {public static void main(String[] args) {List<String> arrayList = new ArrayList<>();arrayList.add("Java");arrayList.add("C");arrayList.add("C++");for (String value : arrayList) {System.out.println("Language Name: " + value);}}}
Output:
Language Name: Java Language Name: CLanguage Name: C++
For each loop, we don't need to specify the array index. There is no need to tell us how many times the loop should be executed or what Is the condition, the array index will start from and where it will end. For each loop automatically do this task. The loop updates the value of the array index into the variable each time.