1class AssignmentOperator {
2 public static void main(String[] args) {
3
4 char[] vowels = {'a', 'e', 'i', 'o', 'u'};
5 // foreach loop
6 for (char item: vowels) {
7 System.out.println(item);
8 }
9 }
10}
1String[] myArray = {"Enhanced for loops", "are cool", "and save time!"};
2
3for (String myValue : myArray) {
4 System.out.println(myValue);
5}
6
7/*Result:
8Enhanced for loops
9are cool
10and save time!
11*/
1As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection of elements including arrays.
2
3Syntax :
4for(declaration : expression) {
5 // Statements
6}
7Declaration − 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.
8Expression − This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.
1for (int i=0; i < array.length; i++) { System.out.println("Element: " + array[i]);}