Retrieving Elements from Collection in Java- For-each loop


The ‘for-each’ loop is used to iterate over a set of elements that is stored in a data structure.

Syntax

for (element e: collection) {
   System.out.println(e);
}

Example

Following is an example −

 Live Demo

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);
   }
}

Output

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.

Updated on: 14-Sep-2020

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements