The Enhanced For Loop

In the field of information technology, what counts more is the early adaptation of the new features that come with every new version of software. Coming up with the JDK 1.5 (tiger) release of Java is a new feature of the enhanced for loop. Let see how it works!

In the enhanced for loop, the array index is not necessary for the retrieval of an array element:

int arr[5] = {2,4,8,16,32}; for (int i=0; i<5; i++)                System.out.println("Output: " + arr[i]);

Now, you can save a few keystrokes and retrieve an array element thusly:

 for(int a:arr)                      //  check syntax, it's colon not semi-colon                 System.out.println("Output: "+ a);

The enhanced for loop also works with collection frameworks. So instead of using Iterators (which are unually used to get elements out of a collection), you can do something like this:

Vector vec = new Vector();                vec.addElement(new Integer(2));                vec.addElement(new Integer(4));                for(Object obj:vec)                                                System.out.println("Output: "+(Integer)obj);
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: