What is Optional in Java 8, and how is it used?

Optional<T> is a container class introduced in Java 8 to explicitly represent the presence or absence of a value, offering a safer, more expressive alternative to returning or checking for null.

Key Points: • An Optional is created with Optional.of(), Optional.ofNullable(), or Optional.empty(), depending on whether the value is known to be non-null. • isPresent() and the more functional ifPresent(Consumer) let you check or act on a value only when it exists. • orElse(), orElseGet(), and orElseThrow() supply fallback behavior when the Optional is empty. • map() and filter() can be chained on an Optional to transform or conditionally clear its contained value without manual null checks. • Optional is best used as a return type for methods that might not produce a result, not as a field type or method parameter.

Example: A repository method like findUserById(id) can return Optional<User> instead of a possibly-null User, forcing callers to explicitly handle the not-found case via orElseThrow() or orElse(defaultUser).

Code Example:

Optional<User> user = userRepository.findById(42);

String name = user.map(User::getName)
        .orElse("Unknown User");

Interview Tip: A concise interview answer is:

"Optional is a wrapper that makes the possible absence of a value explicit in a method's return type, instead of silently returning null. I create it with of() or ofNullable(), then use orElse(), orElseThrow(), or map() to handle both the present and absent cases without scattering null checks through the code."