☕ Java Intermediate

What is Optional in Java?

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().