- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How does the java "for each" loop works
As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) { // Statements }
Declaration − The newly declared block variable is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
Example
public class Test { public static void main(String args[]) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { System.out.print( x ); System.out.print(","); } System.out.print("
"); String [] names = {"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }
Output
This will produce the following result −
10, 20, 30, 40, 50, James, Larry, Tom, Lacy,
- Related Articles
- How does the Java “foreach” loop work?
- How to iterate a Java List using For-Each Loop?
- How to use for each loop through an array in Java?
- How to iterate a List using for-Each Loop in Java?
- Retrieving Elements from Collection in Java- For-each loop
- How does the MD5 Algorithm works?
- Java for loop
- How does digital thermometer works?
- How to use ‘for loop’ in Java?
- Java labelled for loop
- Java infinite for loop
- How does jQuery event namespace works?
- How does JavaScript focus() method works?
- How does Secure Hash Algorithm works?
- How does == operator works in Python 3?

Advertisements