Friday, 11 November 2016

What is For-Each Loop In Java ?

Previously we have discussed about

Here we learn about For-Each In Java, but we must also know What is Iterator Inteface In Java ? and What is Collection Interface In Java ?
For-Each Loop (Advanced For Loop)

Syntax of for-each loop:
for(data_type variable : array | collection){} 

If you won’t be modifying the contents of a collection or obtaining elements in reverse order, then the for-each version of the for loop is often a more convenient alternative to cycling through a collection than is using an iterator.

For-Each can cycle through any collection of objects that implement the Iterable interface. Because all of the collection classes implement this interface, they can all be operated upon by the for.

The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
The for-each loop introduced in Java5.

Example of for-each loop:

import java.util.ArrayList;

public class ForEachLoopExample {

public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Java");
list.add("C++");
list.add("Python");
System.out.println("Traversing Collection Using For-Each Loop : ");
for(String s : list){
System.out.println(s);
}
System.out.println("\nTraversing One Dimensional Array Using For-Each loop : ");
int arr[]={10,12,14,16};  
for(int i : arr){
System.out.println(i);
}
}

}

Program Output:

Traversing Collection Using For-Each Loop : 
Java
C++
Python

Traversing One Dimensional Array Using For-Each loop : 
10
12
14
16

      
Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment