Video in progress

Why was Optional invented?

Optional is there to show in a method's signature, openly, that "a value may or may not be present". It is mostly used as a return value, so the caller doesn't forget the empty case.

📖 Answer

If an ordinary method returns null, you only know it from the documentation (or from an NPE). Optional says it through the type:

Optional<User> findByEmail(String email);   // it may not be found: that's visible right away

On the caller's side:

String name = repo.findByEmail(email)
        .map(User::name)
        .orElse("mehmon");

repo.findByEmail(email)
        .ifPresent(u -> mailer.send(u, "Xush kelibsiz"));

User u = repo.findByEmail(email)
        .orElseThrow(() -> new NotFoundException(email));

Spring Data JPA's findById also returns an Optional, which is where you'll see it most.

Optional is not full protection against NPE. You can still assign null to a variable of type Optional, and you should never do that. It only expresses the intent that "it may be empty".