Core Java Refresher: java.util.Optional<T>

Optional<T> is a generic class introduced in Java 8 to represent a value that may or may not be present, reducing the risk of NullPointerException.

Key Points

Key Methods

  1. public T orElseThrow()

  2. public T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable

Supplier Functional Interface

Custom Exception Example (As Provided, Well-Formatted)

public class UserService {
    private final UserDao userDao;

    public UserService(UserDao userDao) {
        this.userDao = userDao;
    }

    public User findUserById(Long userId) {
        return userDao.findById(userId).orElseThrow(() -> new ResourceNotFoundException("Invalid User Id"));
    }
}

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}


1. Spring Boot in More Detail

Spring Boot is a framework that simplifies Spring application development by providing auto-configuration, standalone applications, and production-ready features.

Core Features