☕ Java Intermediate

What is an Iterator in Java?

Why Interviewers Ask This

This tests whether you can apply Java knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.

Answer

An Iterator is an object that enables traversing a collection one element at a time without exposing the underlying data structure. The Iterator interface has three methods: hasNext() (returns true if more elements exist), next() (returns the next element), and remove() (removes the last element returned by next() — the safe way to remove during iteration). To get an iterator: Iterator<String> it = list.iterator();. Iterating with an iterator while modifying the collection through the collection itself throws ConcurrentModificationException. Use it.remove() instead of list.remove() for safe removal during iteration.

Common Mistake

Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your Java experience.