Optional<T> is a container object that may or may not hold a non-null value, giving Java 8 code an explicit, type-safe way to represent absence instead of relying on null and risking a NullPointerException.
Key Points: • Optional.of(value) wraps a known non-null value and throws NullPointerException if given null. • Optional.ofNullable(value) safely wraps a value that might be null, producing an empty Optional in that case. • Optional.empty() explicitly represents "no value" without using null at all. • orElse(default), orElseGet(supplier), and orElseThrow() provide ways to supply a fallback or raise an exception when the value is absent. • ifPresent(consumer) and the Java 9+ ifPresentOrElse() run code conditionally based on whether a value exists, avoiding manual null checks.
Example: Optional.ofNullable(user.getAddress()).map(Address::getCity).orElse("Unknown") safely digs into a possibly-null address and falls back to "Unknown" instead of throwing a NullPointerException.
Code Example:
Optional<String> name = Optional.ofNullable(getUserName());
String result = name.orElse("Guest");
name.ifPresent(n -> System.out.println("Hello, " + n));Interview Tip: A concise interview answer is:
"I wrap a possibly-null value with Optional.ofNullable(), then use methods like orElse(), orElseThrow(), or ifPresent() to handle the absent case explicitly instead of checking for null. It makes the possibility of a missing value visible in the type system and pushes callers to handle it deliberately rather than risking a NullPointerException."