☕ Java Intermediate

What is Optional in Java?

Why Interviewers Ask This

Mid-level Java roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

Optional<T> is a container object that may or may not contain a non-null value, introduced in Java 8 to reduce NullPointerExceptions. Instead of returning null from a method when no value is available, return Optional.empty(). Callers are then forced to explicitly handle the empty case: optional.isPresent(), optional.get() (throws if empty), optional.orElse(defaultValue), optional.orElseGet(supplier), optional.orElseThrow(). Optional supports functional operations: optional.map(), optional.filter(), optional.ifPresent(). Do not use Optional as a field type or method parameter — use it only as a return type. Do not call get() without checking isPresent().

Pro Tip

Back up your answer with a specific project or situation. Saying 'In my last Java project, I used this when...' immediately makes your answer more credible and memorable.