Friday, July 17, 2009

TIPS AND TRICKS

Using Enhanced For-Loops with Your Classes

The enhanced for-loop is a popular feature introduced with the Java SE platform in version 5.0. Its simple structure allows one to simplify code by presenting for-loops that visit each element of an array/collection without explicitly expressing how one goes from element to element.
Because the old style of coding didn't become invalid with the new for-loop syntax, you don't have to use an enhanced for-loop when visiting each element of an array/collection. However, with the new style, one's code would typically change from something like the following:

for (int i=0; i<=array.length; i++) {
System.out.println("Element: " + array[i]);
}
To the newer form:

for (String element : array) {
System.out.println("Element: " + element);
}

Assuming "array" is defined to be an array of String objects, each element is assigned to the element variable as it loops through the array.

These basics of the enhanced for-loop were covered in an earlier Tech Tip: The Enhanced For Loop

By - Ramesh

No comments: