package com.kt4study.corejava.loop;
import java.util.ArrayList;
/**
* @author kt4study.blogspot.co.uk
*
*/
public class ForEachLoopExample {
public static void forEachDemo(){
//Iterate ArrayList with For Each Loop
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Hello World");
arrayList.add("kt4study.blogspot.co.uk");
for (String element : arrayList) {
System.out.println("Element from ArrayList :: " + element);
}
//Iterate One Directional Array with For Each Loop
int intArray[] = { 15, 6, 4 };
for (int element : intArray) {
System.out.println("Element from OneDirectionalArray :: "+ element);
}
//Iterate Multi Directional Array with For Each Loop
int[][] intMultiArray = new int[2][2];
intMultiArray[0][0] = 10;
intMultiArray[0][1] = 12;
intMultiArray[1][0] = 14;
intMultiArray[1][1] = 16;
for (int[] array : intMultiArray) {
for (int element: array) {
System.out.println("Element from MultiDirectionalArray :: " + element);
}
}
}
public static void main(String[] args) {
ForEachLoopExample.forEachDemo();
}
}
|
Output →
Element from ArrayList :: Hello World
Element from ArrayList :: kt4study.blogspot.co.uk
Element from OneDirectionalArray :: 15
Element from OneDirectionalArray :: 6
Element from OneDirectionalArray :: 4
Element from MultiDirectionalArray :: 10
Element from MultiDirectionalArray :: 12
Element from MultiDirectionalArray :: 14
Element from MultiDirectionalArray :: 16
No comments:
Post a Comment