Enhanced for loop in Java
The enhanced style for can only cycle through an array sequentially, from start to finish.It is also known as the enhanced for loop. The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection (Collections are not covered in these pages). It can also be used for arrays, as in the above example, but this is not the original purpose.
Enhanced for loops are simple but inflexible. They can be used when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element.
Syntax
for( Datatype item : array )
{
// body of loop;
}- Datatype : The Datatype of the array/collection
- Item : Each item of array/collection is assigned to this variable
- Array : An array or a collection
Code Snippet
//Enhanced for loop in Java
public class App {
public static void main(String args[]) {
int numbers[] = { 10, 20, 30, 40, 50, 60, 70 };
for (int n : numbers) {
System.out.println(n);
}
}
}