Top 5 frequently asked questions on Iterator Interface in Java

Q #1) What is the Iteration in Java?

Answer: An iteration is a process by which a code block is repeatedly executed until a given condition holds or doesn’t exist. Using iteration you can traverse through a sequence of elements or process the data.
Q #2) How many types of Iterators are there in Java?
Answer: Iterators are used to traverse through the collections in Java.
There are three types of iterators in Java:
  • Enumerators
  • Iterators
  • ListIterators
Q #3) How do I use an Iterator in Java?
Answer: In order to use the iterator to traverse through the collection, first, you have to get the iterator using the iterator() method of the specified collection.
Then you can use the hasNext() and next() methods of the iterator to get the element.
Q #4) Why Iterator is used instead of for loop?
Answer: Both the iterator as well as for loop is used to repeatedly execute a specific code block. But the main difference is that in for loop you cannot alter or modify the contents of the collection. Even if you attempt to modify it, it will throw concurrentModificationException. Using iterator you can remove an element from the collection.
Q #5) Why do we need Iterator in Java?
Answer: Iterator helps you to retrieve the elements in the collection or a container without the programmer having to know the internal structure or working of the collection. They are more elegant, consume less memory and also the programmer is spared of in writing lengthy code.
Secondly, the elements can be stored in the collection in any fashion but using an iterator, the programmer can retrieve them just like a list or any other sequence.
If you want to read more about iterator in Java, then click here. And to know the difference between iterator and iterable then click here.