The ‘for-each’ loop is used to iterate over a set of elements that is stored in a data structure.
for (element e: collection) { System.out.println(e); }
Following is an example −
public class Demo { public static void main(String[] args) { int[] my_vals = {5, 67, 89, 31, -1, 2, 0}; int sum = 0; for (int number: my_vals) { sum += number; } System.out.println("The sum is " + sum); } }
The sum is 193
A class named Demo contains the main function that defines an integer array with certain values. A sum is initially defined as 0, and the array is iterated over, and every element in the array is added to the sum. This final result is displayed on the screen.