Optional

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Optional<T> is a container object that may or may not contain a non-null value.
  • It was introduced in Java 8 to help developers avoid NullPointerExceptions.
  • Instead of returning null when a value isn’t found, methods should return an empty Optional.

Concept

Before Java 8, if you called userRepository.findById(99), and user 99 didn’t exist, the method returned null. If you forgot to write an if (user != null) check, your app crashed with a NullPointerException (NPE).

Optional forces you to acknowledge that the value might not be there. If a method returns Optional<User>, the compiler effectively warns you: “I might have a User, or I might be empty. You must explicitly handle both scenarios.”

It provides functional methods like ifPresent(), orElse(), and orElseThrow() to handle the contents cleanly.

Examples

import java.util.Optional;

public class OptionalExample {
    
    // Simulating a DB call
    public static Optional<String> findUser(int id) {
        if (id == 1) return Optional.of("Alice");
        return Optional.empty(); // Safely return empty instead of null
    }

    public static void main(String[] args) {
        
        Optional<String> userOpt = findUser(99);
        
        // --- 1. The BAD way (Defeats the purpose) ---
        if (userOpt.isPresent()) {
            System.out.println(userOpt.get());
        }
        
        // --- 2. The GOOD way (Functional) ---
        // Do something only if present
        userOpt.ifPresent(u -> System.out.println("Found: " + u));
        
        // Provide a fallback value if empty
        String name = userOpt.orElse("Guest");
        System.out.println("Welcome, " + name);
        
        // Throw a specific exception if empty
        try {
            String existingUser = userOpt.orElseThrow(() -> new IllegalArgumentException("Not found"));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
}

Interview Questions

Q: Should you use Optional as a field in a class (e.g. private Optional<String> email)?
A: No. Optional was specifically designed to be used as a method return type to indicate that a result might be absent. It is not Serializable, so using it as a field in an entity or DTO breaks serialization frameworks (like JSON parsing or database mapping). Fields should be standard types (can be null), and the getter can return an Optional if desired: public Optional<String> getEmail().

Q: What is the difference between Optional.of() and Optional.ofNullable()?
A: Optional.of(value) strictly requires a non-null value. If you pass null into it, it will immediately throw a NullPointerException.
Optional.ofNullable(value) is safe. If the value is present, it returns an Optional containing the value. If the value is null, it returns Optional.empty().