View RSS Feed

My Java Tips

Enhanced for-loop (Java 5.0)

Rate this Entry
by , 11-20-2011 at 05:14 PM (990 Views)
Java 5.0 introduced an enhanced for-loop. In this post, I'll write about it.


The enhanced for loop provides a 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.

The new for loop makes programming simpler. For example, if you want to print each element for an array, you used to do that with a for loop in the following way:

Java Code:
for (int i=0; i    System.out.println("Element: " + array[i]);

}
The enhanced for loop makes the same task very simple as shown below:

Java Code:
for (String element : array) {

    System.out.println("Element: " + element);

}

Submit "Enhanced for-loop (Java 5.0)" to Facebook Submit "Enhanced for-loop (Java 5.0)" to Digg Submit "Enhanced for-loop (Java 5.0)" to del.icio.us Submit "Enhanced for-loop (Java 5.0)" to StumbleUpon Submit "Enhanced for-loop (Java 5.0)" to Google

Categories
Java SE

Comments