example of enhanced for loop in java

Asked on March 18, 2015
Can anyone tell me what is enhanced for loop and how may I use it in my code? If possible then please send me a demo code. Thanks

Replied on March 18, 2015
Enhanced loop is used with generic class introduced in Java 5. You must know generics before understanding enhanced loop. To understand enhanced loop, suppose we have a Class as

public class User {
   int id;
   String name;
  public User(int id, String name){
        this.id = id;
        this.name= name;

Set some sample values as

User user1 = new User(1,"A");
User user2 = new User(2,"B");

Put these values in List

List<User> list = new ArrayList<User>();

We can iterate is with enhanced loop which has been introduced in Java 5 with Generics as

for(User user: list) {
  System.out.println("id:"+ user.id+", name:"+ user.name);

The above loop is same as old one given below.

for(int i=0;i<list.length(); i++){
   User user = list.get(i);
   System.out.println("id:"+ user.id+", name:"+ user.name);

Replied on March 19, 2015
Java language has a second type of for loop called the enhanced for, it was introduces in Java 5.0(Tiger). Enhanced for loop make it easier to iterate over all the elements in an array and collection.

Suppose you have a array ...

String[] nameArray = {"Bucky", "Mary", :Mark"};

Syntax for enhanced for...

for(String name : nameArray) { // code is here}

String- the elements in the array must be compatible with the declared variable type.

Name- With each iteration, a different element in the array will be assigned to the variable "name".

Colon(:)- the colon(:) means IN.

nameArray- the collections of the elements that you want to iterate over.

Replied on March 19, 2015
Traditional for loop:

for (int i=0; i < array.length; i++) {
    System.out.println("Element: " + array[i]);

Enhanced for loop:

for (String element : array) {
    System.out.println("Element: " + element);

Replied on March 19, 2015
See this example for better understanding 

public class EnhancedForLoopTest {
public static void main(String[] args) {
String[] nameArray = new String[3];
nameArray[0]= "Atul";
nameArray[1]= "mukul";
nameArray[2]= "vipul";
for(String name : nameArray){

Write Answer

©2024 concretepage.com | Privacy Policy | Contact Us