This is similar to a for loop except that it has some enhanced features. It can be used to iterate over the elements of a collection without knowing the index of each element.
It dosn't need to know the size of the collection.
In a simple word java for loop has an alternative syntax that makes it easy to iterate through arrays and collections.
Syntax:
for(type variableName: arrayName){
// statement or code to be executed
}
// Java program to print the element of the Array
class Simple{
public static void main(String args[]){
//Declaring an array
int array[] = {11,22,33,44,55,66,77,88,99};
//Printing array elements using for-each loop
for(int i:array){
System.out.println(i);
}
}
}
Output:
11
22
33
44
55
66
77
88
99
// Java program to print the element of the Array
class Simple{
public static void main(String args[]){
//Declaring an array
String name[] = {"Raj" , "Raja" , "Ankita" , "Komal" , "Jackson"};
//Printing array elements using for-each loop
for(String i:array){
System.out.println(i);
}
}
}
Output:
Raj
Raja
Ankita
Komal
Jackson