- 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);
}
}
}
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
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);
}
}
}
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
Geetha
Aarya
Ajay
No comments