Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Java 8 — Optional, Date/Time API, Method Refs

What is Optional actually for, and what are the anti-patterns interviewers want you to avoid?

Level II · JuniorJava 8 — Optional, Date/Time API, Method Refs
Short answer

Optional is a deliberate API signal that a return value may be absent, pushing callers to handle the empty case instead of risking an NPE — it's best used as a method return type.

Explanation

The anti-patterns are: using it as a field or method parameter (adds overhead and another null state, since Optional itself can be null), calling get() without checking (just a disguised NPE), and using Optional for collections (return an empty list instead). Prefer map/flatMap/orElseGet/ifPresent over isPresent()+get(), and use orElseGet over orElse when the default is expensive to build.

Common mistakes
  • Using Optional as a field or parameter type.
  • Calling get() without checking, which is just a null check in disguise.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Java 8 — Optional, Date/Time API, Method Refs.

Practise free

More on Java 8 — Optional, Date/Time API, Method Refs