
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve Elements from Collection in Java Using 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 −
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.
Advertisements