As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
Syntax :
for(declaration : expression) {
// Statements
}
Declaration − The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
class Main {
public static void main(String args[]){
int arr[]={1,2,3,4,5};
for (int num : arr) {
System.out.println(num);
}
}
}
for(int name: array)
{
System.out.print(name + " ");
}
String[] myArray = {"Enhanced for loops", "are cool", "and save time!"};
for (String myValue : myArray) {
System.out.println(myValue);
}
/*Result:
Enhanced for loops
are cool
and save time!
*/