Java Iterator — Free Java Tutorial

Learn Java Iterator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Java Iterator — Free Java Tutorial

Learn Java Iterator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Java Iterator in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Java Iterator in Java

Iterator<T> defines a standard way to traverse a collection: hasNext() checks if more elements remain, next() returns the next element, remove() removes the last returned element.

Iterable<T> (implemented by all collections) enables the enhanced for-each loop. Any class implementing Iterable must return an Iterator from iterator().

The key advantage of Iterator.remove() is safe removal while iterating — removing from a collection during for-each throws ConcurrentModificationException.

ListIterator extends Iterator with bidirectional traversal (previous(), hasPrevious()) and allows set() and add() operations during iteration.

Java Iterator — Syntax

// Iterator usage
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (shouldRemove(s)) it.remove(); // safe removal
}

// For-each uses Iterable internally
for (String s : list) { ... }

// Custom Iterable class
class Range implements Iterable<Integer> {
    public Iterator<Integer> iterator() { ... }
}

Learn Java Iterator step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →