NoSuchElementException in Java — What It Means and How to Fix It

What Java's NoSuchElementException means and how to fix it.

Published November 3, 2026

NoSuchElementException is thrown when you ask for an element that does not exist: iterator.next() past the end, Optional.get() on empty or Scanner reading with no input.

What it means and why it happens

Typical causes: empty collections, empty Optionals and exhausted iterators.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.util.NoSuchElementException: No value present

Practical examples

Code that triggers it

Optional<String> o = Optional.empty();
o.get();

The fix

Optional<String> o = Optional.empty();
String v = o.orElse("default");
o.ifPresent(System.out::println);

Check before next()

while (it.hasNext()) { use(it.next()); }

Common mistakes

  • Calling Optional.get() without isPresent.
  • Calling next() without hasNext().
  • Scanner.nextLine() with no input.

Key takeaways

  • NoSuchElementException: NoSuchElementException is thrown when you ask for an element that does not exist: iterator.next() past the end, Optional.get() on empty or Scanner reading with no input.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Optional.get alternatives?

orElse, orElseGet, orElseThrow, ifPresent.

How do I find which line caused NoSuchElementException?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles