For Each loop in java 1.5

The for-each loop, or enhanced for loop, is new feature in JDK 1.5 to remove clutter and possible errors, in iterating over collections.This will not provide any new functionality .It is just making our code more easy.It allow to create one variable which will iterate over array or collection.By this we can do nested iteration.

JDK 5.0 provides a special kind of for loop for access through all the elements of it.

 
Syntax 

For(vaiable : collection){ Statements; } 
Example:

  int[] a={1,2,3,4,5,6,7,8,9,0};
Using for Each loop :-

  for(int i : a){
    System.out.println(i);</em>
  }  

using Simple for loop :-

for(Iterator itr = a.iterator(); i.hasNext(); ) {
  String item = i.next();
  System.out.println(item);one more example will clear you more on this.

Using Foreach with Arrays  :-

String[] letters = { "v", "i", "n" , "a" , "y" };
for (String letter: letters)
   System.out.println(letter.charAt(0));

Vinay

I am an Oracle ACE in Oracle ADF/Webcenter. Sr Java Consultant-working on Java/J2EE/Oracle ADF/Webcenter Portal/ content and Hibernate for several years. I'm an active member of the OTN JDeveloper/Webcenter forum. Passionate about learning new technologies. I am here to share my knowledge. Give your views and suggestion on [email protected] .

More Posts - Website

Follow Me:
TwitterLinkedInGoogle PlusYouTube