Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Aug 7, 2007

The Enhanced for loop in Java 1.5 (5.0)

There have been a lot of enhancements to existing features in Java 1.5 (5.0). One of the simplest improvements is to the most commonly used for loop.

Here's how it worked prior to version 1.5:

vec is a Vector

SomeObject obj;

for(int i=0;i<vec.size();i++)
    obj = (SomeObject) aVec.elementAt(i);
    //code to use obj
Now, here's how it works in version 1.5:

for (Object aVec : vec)
    obj = (SomeObject) aVec;
    //code to use obj
As you can see, the loop incrementor is now handled implicitly.

MS Sridhar
Thanks for your registration, follow us on our social networks to keep up-to-date