Wednesday, 16 November 2011

Enhanced for loop

Enhanced for loop:

1. This new feature added in Java1.5

2. Also callied as "for each loop".

3. It allows as to iterate through collection without having to create a iterator or without having to calculate beginning and end conditions for counter variable.

For example, 

In normal for loop,

class sample {
    public static void main(String args) {
        int[] var = {1, 9, 18, 27 };
        for( int i = 0; i < var.length; i++) {
            System.out.println("values :" +var[i]);
        }
    }
}
       
For each loop,

class sample {
    public static void main(String args) {
        int[] var = {1, 9, 18, 27 };
        for( int i : var) {
            System.out.println("values :" +var[i]);
        }
    }
}

Here, no need to check var length. Its easy to adapt for loop to for each loop.


But, It contains some disadvantages, follows

1. for each loop iterate only sequencialy. cant get first and third value using for each. [ Step value can not be incremented ]

2. Backward traversal is not possible.



Reference :

http://www.javabeat.net/articles/32-new-features-in-java-50-1.html

No comments:

Post a Comment