Saturday, September 10, 2005

Enhanced for loop in J2SE 5.0

The enhanced for makes it easier to iterate over all the elements in an array or other kinds of collections. Look at this simple example:
public class EnFor
{
public static void main(String[] args)
{
String[] cities =
{"Pune", "Mumbai", "Bangalore", "Hyderabad"};

for (String name : cities)
{
System.out.println(name);
}
}
}
If we analyse the for code, then the following happens:
(a) a String variable called name is created and set to null. The variable that you declare must be compatible with the elements in the array.
(b) Next, the first value in the cities array is assigned to name.
(c) The body of the loop is executed.
(d) The next value in the cities array is assigned to name. Remember, with each iteration, a different element in the array will be assigned to name.
(e) This is repeated as long as there are elements in the array.

Note: The : in the for, means "IN". Also, what follows the : must be a reference to an array or other collection.
Technorati Tags:
Blogs linking to this article

0 Comments:

Post a Comment

<< Home