I've been getting confused about the use of Optional.of() versus Optional.ofNullable() in Java. It's a little counterintuitive to me that Optional.of() can throw a NullPointerException. Can someone explain the real application of Optional.of() and why we even need it when there's already Optional.ofNullable()? Aren't both of them used to handle null values?
2 Answers
If you are pretty sure that the value should never be null, then go with Optional.of(). If not, Optional.ofNullable() is your best bet. This clarity helps document your intent and keeps track of assumptions about the values throughout your code. If your value is genuinely expected to be non-null and you use ofNullable(), any bugs that turn that value null might slip by under the radar.
The main purpose of Optional.of() is for situations where you're certain that the value you're passing is not null. It's a way of documenting that expectation and failing fast if it’s violated, which is particularly useful in lambdas and functional programming. On the other hand, if you might have a null value, that's where Optional.ofNullable() comes in—it's more flexible and helps avoid unexpected null pointer exceptions later in your code.
But isn't that what orElseThrow() is for? I feel like developers should handle this kind of null-checking themselves, as I've seen more NullPointerExceptions with Optional.of() than from using orElseThrow().
If you're confident it's non-null, why bother with Optional at all? Shouldn't it just be treated as mandatory?