Menu
Question Index
...

Compare the following programs?

import java.util.*;
public class ForEachLoop
{
    public static void main(String[] args)
    {
        List<String> strList = new ArrayList<String>();
        strList.add("M");
        strList.add("E");
        strList.add("R");
        strList.add("I");
        strList.add("T");

        for(String obj : strList)
        {
            System.out.print(obj + " ");
        }
    }
}
import java.util.*;

public class Iterator
{
    public static void main(String[] args)
    {
        List<String> strList = new ArrayList<String>();
        strList.add("M");
        strList.add("E");
        strList.add("R");
        strList.add("I");
        strList.add("T");

        java.util.Iterator<String> it = strList.iterator();
        while(it.hasNext())
        {
            String obj = it.next();
            System.out.print(obj + " ");
        }
    }
}


Both ForEachLoop and Iterator produce same output.
ForEachLoop and Iterator produce different output.
Iteratorwill compile and runs with out any error, butForEachLoop will gives compilation error.
ForEachLoop will compile and runs with out any error, but Iterator will gives compilation error.
Both ForEachLoop and Iterator will fails to execute.

Doubts

Problems

Topic: Java Iterator

Read this topic
Take test on this topic

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App