What You Might Not Know About Optional

How Optional can help you remove the nasty null pointer errors

Milos Zivkovic
Javarevisited

--

Photo by Andres Ayrton from Pexels
· What’s the correct usage of ofNullable?
· Don’t return null, use Optional
· Why is Optional#of necessary?
· Why Optional#of throws NullPointerException?
· You shouldn’t use Optional for method arguments

What’s the correct usage of ofNullable?

How did you represent absent values before Optional? Yes, you used null. The code would look something like this:

The problem Optional solves is the absence of value. Look at the following example.

The first line will cause NullPointerException on the caller. Line using Optional on the contrary won’t. You need to unwrap the Optional and handle the absence.

--

--