elvis
elvis

Reputation: 1178

Can I get NullPointerException when use isEmpty() with Java Optional?

I'm learning about Optional<> used in implementation with JPA and Hibernate. And I see a lot of developers are using these 2 methods isEmpty() or isPresent() like here:

private void checkCustomer(UUID customerId) {
    Optional<Customer> customer = customerRepository.findCustomer(customerId);
    if (customer.isEmpty()) {
        log.warn("Could not find customer with customer id: {}", customerId);
        throw new CustomerException(...);
    }
}

I want to know if this isEmpty() method checks if the customer is null or empty. For example if there is no customer with this id in the database, then the variable customer will be null or empty? I ask that because if the isEmpty() method checks if the customer is empty, but the customer is null, in this case can I get a NullPointerException at this line customer.isEmpty()? Or if I use customer.isPresent() can I get a NullPointerException?

Upvotes: 0

Views: 2472

Answers (2)

Alexander Ivanchenko
Alexander Ivanchenko

Reputation: 28988

I want to know if this isEmpty() method checks if the customer is null or empty

As the method name suggests, it checks if the optional is empty or not. The optional object itself shouldn't be null, otherwise it defeats the whole purpose of using Optional and you end-up with a muddy code.

In a nutshell, Optional is a container of data wrapped around something nullable, so you can safely interact with it and the wrapped value.

Optional is supposed to have two states: either contain a value, or not. An empty optional represents the absence of data (which can also represented with a null value in a code which doesn't uses Optional).

Like any other object, optional might be assigned with a value of null, but it goes against the design goal of the Optional type. That's something that should never be the case, if your methods are properly designed, don't return null instead of an empty optional.

You might be interested in reading:

Upvotes: 1

Dima Katzir
Dima Katzir

Reputation: 51

In general, Optional.isEmpty() and Optional.isPresent() will not throw NullPointerException by themselves.
However, you need to verify that Optional<Customer> customer variable is actually receiving Optional<> value from returning method. In case the method returns null the exception will be thrown

Upvotes: 0

Related Questions