Sunday, April 7, 2013

Java Enhanced For Loop Example

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





 

3 comments :

  1. Thanks, so simple example

    ReplyDelete
  2. It 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.
    java training in chennai | java training institutes in chennai

    ReplyDelete

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.