|
In Jdk1.5 a new forEach loop is introduced to simplify the iteration process for the collections. The syntax of the for each loop is as follows:-
for ( Objecttype obj : collection )
All the objects of the collection is assigned to the obj in a sequence. The main advantages of the loop is that we don't have to type cast the objects from the collection to the desired type. The following example will demonstrate the use of the forEach loop.
package com.visualbuilder;
import java.util.ArrayList; import java.util.List;
public class ForeachExample {
public static void main(String[] args) { List<String> array=new ArrayList<String>(); array.add("visual"); array.add("builder"); for(String object: array){ System.out.println(object); } } }
Output:-
The program will display the following output.
visual
builder |