• Using enhanced for loops we are just simplify the regular for loop and operation of for loop.
  • Enhanced for loops are applicable to any object that maintains group of elements and supports indexes.
  • Enhanced for loops are used where ever it is required to access all the elements from the beginning till ending automatically from array or from any object representing group of elements along with index.

Enhanced for loop to iterate Array:

 package com.instanceofjavaforus;

public class EnhancedForloop {

    public static void main(String args[]){
      
        int x[]={1,2,3,4,5,6};
      
        for(int i:x){
            System.out.println(i);
        }
      
    char ch[]={'a','b','c','d','e'};
  
    for(char i:ch){
        System.out.println(i);
    }
  
    }
}

output:

1
2
3
4
5
6
a
b
c
d
e

Enhanced for loop to iterate ArrayList:


package com.instanceofjavaforus;

import java.util.ArrayList;
import java.util.Collection;

public class EnhancedForLoopList {

    public static void main(String args[]){
       
    Collection<String> nameList = new ArrayList<String>();
    nameList.add("Ramu");
    nameList.add("Geetha");
    nameList.add("Aarya");
   nameList.add("Ajay");
    for (String name : nameList) {
      System.out.println(name);
    }
    }
}

Output:

Ramu
Geetha
Aarya
Ajay

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu