Monday, August 6, 2007

JAVA 5.0 Enhanced For- Loop

Enhanced FOR-LOOP is a new addition in JAVA 5.0. If you have worked in Visual Basic then you have used FOR-EACH loop in VB. Enhanced For-loop in JAVA5.0 is very similar to For-Each Loop of Visual Basic.

Enhanced for-loop is used to iterate arrays and collections.

Iteration over Arrays :
 The  syntax for iteration over arrays is as following :

for (type variable : array)
{
body-of-loop
}
First we make a function that uses simple/conventional For Loop to add an array of int and returns its sum:

int sumArray( int [] arr )
{
int sumArray=0;
for ( int i=0;i
{
sumArray+=arr[i];
}
return sumArray;
}

If we want to utilize the new Enhanced for-loop( sometimes called For-Each loop or For-In loop) the above function will be like.

int sumArray( int [] arr )
{
int sumArray=0;
for ( int i : arr )
{
sumArray+=i; // here i gets successively each value in array a
}

return sumArray;
}

Iteration over Collections :
 The  syntax for iteration over collections is as following :

for (type variable : collection )
{
body-of-loop
}

For example we have a collection of books in a List and we retrieve it using Iterators using the
conventional for- loop like:

List books = ......
for (Iterator i = books.iterator(); i.hasNext(); )
{
Book book= (Book) i.next();
//..... body of loop ....
}

Its reciprocal syntax using enhanced-for loop will look like,
// Assume there is a List of books available like
List books = ......

for (Book book : books)
{
// /now book has the value for each iteration of list
}

Restrictions of Enhanced For-Loop:
  • It is not possible to traverse more than one structures at the same time. For example two arrays.
  • You can only access only single element at each iteration. You can not have access to more than one elements. Like in case of comparing successive elements in an array.
  • You can not iterate an array backwards. It is forward-only and single step increment.
  • It is not compatible for the earlier versions of the JAVA 5.0.
For more details visit the following link of SUN DOCOMENTATION

No comments: