Understanding foreach loop in Java

>> Sunday, January 8, 2012


To make iteration over arrays and other collections more convenient Java5 extended the basic for loop and it is named as for-each Loop and also called as enhanced for loop or foreach loop.

The for-each loop is used to access each successive value in a collection of values.

This foreach loop is commonly used to iterate over an array or a Collections class (eg, ArrayList).

For-Each loop Syntax is given below

//... Foreach loop over all elements in arr.
for (type var : arr) {
    Body-of-loop
}
Actual working mechanism using indexes in Java4 and equivalent to for loop.
//... For loop using index.
for (int i = 0; i < arr.length; i++) {
    type var = arr[i];
    Body-of-loop
}
In Collections we can use variable as an Object to iterate all elements in the object. Here we can work more progressively with collections. No need to use Iterator.
//... Foreach loop over all elements in arr.
for (type var : coll) {
    Body-of-loop
}
Using iterator we can iterate the elements with specified methods and equivalent to for loop.
//... Loop using explicit iterator.
for (Iterator<type> iter = coll.iterator(); iter.hasNext(); ) {
    type var = iter.next();
    Body-of-loop
}
Advantages of for-each Loop:
  • Less error prone code
  • Improved readability
  • Less number of variables to clean up
Limitations:
  • Cannot be used where the collection is to be altered while traversing/looping through
  • My not be suitable while looping through multiple collections in parallel
  • Example program on for-each loop.

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Google Bookmark Yahoo ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

5 comments:

computers intelligence February 15, 2012 at 8:08 AM  

Hi i have one doubt

How to set the path in environment variables for my own directory? like i am able to set path for C:\Program Files\Java\jdk1.5.0_05, but i am not able to create a permanent path for C:\corejava ie. for my own directory.

GeekDude February 15, 2012 at 6:36 PM  

If you are doing java programs in your own directory then you should give path in Environment Variables and check in System Variables then select path in that . paste the java installed path up to bin as: C:\Program Files\Java\jdk1.5.0_04\bin; ends with semicolon. then click ok.

If you already opened your cmd prompt close it. and Start it again . Now you can able to run your java programs from your own directory.

Hemkant Jagtap February 24, 2012 at 12:02 PM  

Hemkant Jagtap,java is complete object oriented not pure object oriented because we can see hashcode of object, we can't see hashcode of object.

chsekhar July 14, 2012 at 3:29 PM  

hi sir this is chadra sekhar how to get the specfied type of elments of collection which consists of various types of elemnts.
ex:List l1={21,3,4,dsa,fa,afg,33.4,33.5}
i want to get the only string elnts in to another colection please give me solution,

mohammed ali July 28, 2012 at 9:18 AM  

import java.awt.*;
import java.awt.event.*;
class text extends Frame
{
Label l1,l2;
TextField tf1;
TextArea ta1;
text()
{
setTitle("Text Ex");
setSize(250,250);
FlowLayout fl=new FlowLayout();
setLayout(fl);
//create the component
l1=new Label("Enter a Line of text");
l2=new Label("copied Text");
tf1=new TextField(50);
ta1=new TextArea();
//add the components
add(l1);
add(tf1);
add(l2);
add(ta1);
//register the event
Mohammed md=new Mohammed(this);

tf1.addTextListener(md);
setVisible(true);
}//text()

}//text-----Bsnss logic class

class Mohammed implements TextListener
{
text x;
Mohammed(text x)
{
this.x=x;
}
public void textValueChanged(TextEvent te)
{
String s=x.tf1.getText();
x.ta1.append(s+"\n");
// x.ta1.setText(s);
}
}

class MeMohammed
{
public static void main(String[] args)
{
text to=new text();
}
}

//sir can u plz explain the control flow after coming to 'Mohammed' class obj at registration of and the total flow plz.....it is mandatory for me to know...iam ur 5pm batch student of adv java

Post a Comment

Related Posts Plugin for WordPress, Blogger...

Random Posts

JavabynataraJ - Find me on Bloggers.com Find me on blorner.com Technology Blogs JavabynataraJ Backlinks Blogarama - The Blog Directory

  © Blogger template Webnolia by Ourblogtemplates.com 2009

Back to TOP