The Java for-each loop is an enhanced form of the standard for
loop. It was introduced in Java 5.
The for-each loop can be used to iterate over all the elements of an array or the data stored using the classes of Java Collections framework e.g. ArrayList, vector, linkedlist, etc.
The generalized syntax of for-each loop is given below:
//for iterating over an arrayfor(datatypeOfArray var : arrayName){//Statements using the var}//for iterating over a Collectionfor(datatypeOfCollection var : collectionName){//Statements using the var}
The below illustration will help you understand it better.
There is no iterator
i
used in the for-each loop unlike the standardfor
loop.
Let’s print out the names of animals stored in an ArrayList using the for-each loop.
class ForEach {public static void main( String args[] ) {ArrayList<String> animals = new ArrayList<>();//Adding the names to the ArrayListanimals.add("Dog");animals.add("Cat");animals.add("Sheep");animals.add("goat");//Printing out using for-each loopfor(String var : animals){System.out.println(var);}}}
Free Resources