Java provides 2 ways of iterating over arrays.
Traditional or old style iteration
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
New style
JDK 5.0 introduces a powerful looping construct that allows you to loop through each element in an array (as well as other collections of elements) without having to fuss with index values.
for (variable : collection)
statement
for (int element : a)
System.out.println(element);
So here we are taking element from array a and dumping it on output.
Note: println prints each element of the array a on a separate line.
You should read this loop as "for each element in a". The designers of the Java language considered using keywords such as foreach and in. But this loop was a late addition to the Java language, and in the end nobody wanted to break old code that already contains methods or variables with the same names (such as System.in).
"for each" vs for
The loop variable of the "for each" loop traverses the elements of the array, not the index values.
The "for each" loop is a pleasant improvement over the traditional loop if you need to process all elements in a collection. However, there are still plenty of opportunities to use the traditional for loop. For example, you may not want to traverse the entire collection, or you may need the index value inside the loop.
No comments:
Post a Comment