Format:
for (type Element:array)
{
SYSTEM.OUT.PRINTLN (Element);
}
Ex
{public static void main (string[] args) {int[] arr = {1, 2, 3, 4, 5}; System.out.println ("----foreach---"); for (int element:arr) {System.out.println (element); } System.out.println ("----foreach------of the two-dimensional array"); Traverse the two-dimensional array int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; For (int[] row:arr2) {for (int element:row) {System.out.println (element); }}//Iterate through the collection in three ways list list<string> list = new Arraylist<string> ( ); List.add ("a"); List.add ("B"); List.add ("C"); SYSTEM.OUT.PRINTLN ("----Mode 1---"); The first way, the normal for loop for (int i = 0; i < list.size (); i++) {System.out.println (List.get (i)); } System.out.println ("----Mode 2---"); The second way, using iterationsIterator<string> iter = List.iterator (); Iter.hasnext ();) {System.out.println (Iter.next ()); } System.out.println ("----mode 3---"); The third way, use the enhanced for loop for (String str:list) {System.out.println (str); } }}
For each in Java