Video in progress
When do you use Optional.of(), Optional.ofNullable() and Optional.empty()?
of(x) when x is definitely not null; if null arrives it throws an NPE immediately. ofNullable(x) when x may be null, and it returns an empty Optional for null. empty() when you deliberately need an empty Optional.
📖 Answer
Optional<String> a = Optional.of("salom"); // there's a value
Optional<String> b = Optional.of(null); // NullPointerException
Optional<String> c = Optional.ofNullable(map.get(key)); // if null, it's empty
Optional<String> d = Optional.empty(); // empty
The rule for choosing is simple:
- the value is produced inside your own code and you're sure it can't be null:
of. If null shows up anyway, the error appears right there, which is good; - a value that comes from outside (
Map.get, a legacy API, JDBC):ofNullable; - a "not found" case in a method:
return Optional.empty();.
A commonly seen wrong way of writing it:
if (user != null) return Optional.of(user);
else return Optional.empty();
That is exactly Optional.ofNullable(user), so write it in one line.
Sign up to mark studied questions and save your progress.