Skip to main content

Posts

Showing posts with the label Enhanced for loop

How To Use For Each Loop

JDK 5.0 provides a special kind of for loop to access through all the elements of it. Syntax For(vaiable : collection){ Statements; } Example:    int []  a= { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 } ;    for ( int  i : a ){      System.out.println ( i ) ;    }

Why final variable in Enhanced for Loop does not act final?

--   public class EnhancedForTest { public static void main(String... args) { String[] strArr = {"A", "B", "C", "D"}; for (final String s : strArr) { System.out.println(s); } } } Since the String s is delcared as final, this code should not compile. However, this is working fine. Why? The enhanced for-loop as shown above is actually just as the following code: public class EnhancedForTest { public static void main(String... args) { String[] strArr = {"A", "B", "C", "D"}; for (int index = 0; index < strArr.length; index++) { final String s = strArr[index]; System.out.println(s); } } }

What Are Restrictions for Enchanced For Loop?

-- You can not use "Enhanced For Loop" to remove elements from a collect or an array. Also, you can not modify the current slot in a collect or an array. It is not usable for loops where you need to replace elements in a list or array as you traverse it. For example, class Program { public static void main(String[] args) { Collection c = new ArrayList (); c.add("A"); c.add("B"); c.add("C"); for(String name : c) { name = "CHANGED"; } for(String name : c){ System.out.print(name); } } } You will see that the ouput still "ABC". All you have done is modified the local reference variable name.

How to use Enhanced for Loop?

-- Using the following link to learn what the Enhanced for Loop is( The For-Each Loop ). The following code is an interesting example of using Enhanced for Loop. The enhanced for loop will go through the array arr and set i to each member of the "int" array. class Program { public static void main(String[] args) { int []arr = {1,2,3,4}; for ( int i : arr ) { arr[i] = 0; } for ( int i : arr ){ System.out.println(i); } } }