Home Help Java F Java foreach

Related Tutorials


 
 

Share on Google+Share on Google+

Java foreach

Advertisement
Iterating over a collection of objects and performing some action on each object is one of the most common task while programming .

Java foreach

     

 

Iterating over a collection of objects and performing some action on each object is one of the most common task while programming. There are many different iteration techniques that requires to type a good amount of characters and thus costs you more time. Java 1.5 provides many new features including a new way of iterating over a collection of elements. This new feature is known as for-each loop that can be considered as enhanced for loop. This new syntactical construct has been designed to simplify iteration over a collection of elements. For-each construct is used with generics elegantly that takes care of type safety also.

The syntax of for-each loop is shown here:

for(type vaiable : collection){ Statements; } 

and

for (type vaiable: array) { Statements; }

Effective use of the foreach loop depends on parameterized types that you are using. Here is the example that shows the element of the List?s object.

 

List names = new ArrayList();
names.add("a");
names.add("b");
names.add("c");

for (Iterator it = names.iterator(); it.hasNext(); ) {   String name = (String)it.next();   System.out.println(name.charAt(0));

 


Another example shows the for-each loop using the Array?s object.

 

int[] a={1,2,3,4,5,6,7,8,9,0};
  for(int i : a){
  System.out.println(i);
  }

 


Read more at:

http:/www.roseindia.net/java/java-tips/flow/loops/foreach.shtml

 

 

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 9, 2009

Related Tutorials

Discuss: Java foreach  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com