Null pointer exceptions in Java 8

Reading Time: 2 minutes

Probably every single developer has headaches with null pointers, so what is the silver bullet for this problem?

Java 8 introduced a handy way of dealing with this and it’s called Optional object. This is a container type of a value which may be absent. For example, let’s search for some objects in the repository:

Object findById(String id) { ... };

Object object = findById("1"); 
System.out.println("Property = " + object.getProperty());

We have a potential null pointer exception if the object with id “1” is not found in the database. The same example with using Optional will look like this:

Optional<Object> findById(String id) { ... };

Optional<Object> optional = findById("1");
optional.ifPresent(object -> {
    System.out.println("Property = " + object.getProperty());    
})

By returning an Optional object from the repository, we are forcing the developer to handle this situation. Once you have an Optional, you can use various methods that come with it, to handle different situations.

ifPresent()

optional.ifPresent(object -> {
    System.out.println("Found: " + object);
});

We can pass a Consumer function to this method, which is executed when the object of Optional exists.

isPresent()

if(optional.isPresent()) {
    System.out.println("Found: " + optional.get());
} else {
    System.out.println("Optional is empty");
}	

Will return true if we have a non-null value for the Optional object.

Throw an exception when a value is not present

One possible solution for handling null pointer exceptions when the object is not present would be throwing a custom exception for the specific object. All of these custom exceptions should be summarized and handle on a higher level, in the end, they can be shown to the end user.

@GetMapping("/cars/{carId}")
public Car getCar(@PathVariable("carId") String carId) {
    return carRepository.findByCarId(carId).orElseThrow(
	    () -> new ResourceNotFoundException("Car not found with carId " + carId);
    );
}

For that purpose, we can use orElseThrow() method to throw an exception when Optional is empty.

Thanks for reading, I hope it helps and don’t forget always to keep it simple, think simple 🙂