Java Enhanced For Loop Example :
Enhanced For Loop is a more easy way and convenient way to iterate the elements from the collections or Arrays.
I am giving very basic Enhanced For Loop Example below.
The below code is very straight forward how you iterate the elements over the collections/arrays by using
Enhanced For Loop.
Enhanced For Loop Example Code
import java.util.ArrayList;
//Java Enhanced for Loop Example
public class EnhancedForLoopExample {
public static void main(String[] args) {
String[] array = new String[] { "v1", "v2", "v3" };
//Normal for loop iterate elements from the Array
for (int i = 0; i < array.length; i++) {
System.out.println("Normal For Loop : " + array[i]);
}
//Enhanced for Loop iterate elements from the Array
for (String value : array) {
System.out.println("Enhanced For Loop : " + value);
}
//Using generics storing the elements into the ArrayList
ArrayList<String> aList = new ArrayList<String>();
aList.add("v-1");
aList.add("v-2");
aList.add("v-3");
//Normal for loop iterate elements from the ArrayList
for (int i = 0; i < aList.size(); i++) {
System.out.println("Normal For Loop : " + aList.get(i));
}
//Enhanced for Loop iterate elements from the ArrayList
for (String value : aList) {
System.out.println("Enhanced For Loop : " + value);
}
}
}
Output of the Program :
Normal For Loop : v1
Normal For Loop : v2
Normal For Loop : v3
Enhanced For Loop : v1
Enhanced For Loop : v2
Enhanced For Loop : v3
Normal For Loop : v-1
Normal For Loop : v-2
Normal For Loop : v-3
Enhanced For Loop : v-1
Enhanced For Loop : v-2
Enhanced For Loop : v-3
Nice Example
ReplyDeleteThanks, so simple example
ReplyDeleteIt is really a great work and the way in which u r sharing the knowledge is excellent.And i hope this will be useful for many people.. and i am waiting for your next post keep on updating these kinds of knowledgeable things.
ReplyDeletejava training in chennai | java training institutes in chennai