Home Help Java F Java foreach



Java foreach
Posted on: November 9, 2009 at 12:00 AM
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

 

 

Related Tags for Java foreach:


More Tutorials from this section

Ask Questions?    Discuss: Java foreach  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.