Where: declaration: is used to declare the new variable. expression: is the array or collection object to be iterated.
import java.util.ArrayList; import java.util.List; /** * Program to use enhanced for loop example in java. * @author W3spoint */ public class EnhancedForLoopExample { static void enhancedForLoopTest ( List < String > arrayList){ //Enhanced For loop test for (String name : arrayList) { System. out.
With the release of Java version 1.5, Java introduced a new kind of for loop known as enhanced for loop.
After, the first loop is completed the next iteration happens, in the next iteration num [1] is assigned to i where num [1] is 2. Again the statement inside the loop is executed. This time it prints 2 in the output.
The working of the loop is very simple, the header of the loop specifies that for each iteration, assign the next element in the array to int type variable i and then execute the statement.
As you can see that the new way of iterating is simple and easy to use.
Now, you have learned the use of a for-each loop to iterate through an array of elements. Moreover, we can also use for-each loop or enhanced for loop to iterate through the content of a collection in Java. If you don’t know what is collection framework in Java then you can read more on it.
Java for-loop is a control flow statement that iterates a part of the program multiple times. For-loop is the most commonly used loop in java. If we know the number of iteration in advance then for-loop is the best choice.
Curly braces in for loop is optional without curly braces in for-loop we can take only one statement under for-loop which should not be a declarative statement and if we write declarative statement there then we will get compile-time error.