Explore Courses Blog Tutorials Interview Questions
0 votes
in Java by (3.9k points)

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = <value or null>;

Optional.of(foobar);         // May throw NullPointerException

Optional.ofNullable(foobar); // Safe from NullPointerException

I understand Optional.ofNullable is the only safe way of using Optional, but why does Optional.of exist at all? Why not just use Optional.ofNullable and be on the safe side at all times?

1 Answer

0 votes
by (46k points)
Your question is based on suspicion that the code which may throw NullPointerException is worse than the code which may not. This hypothesis is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will symbolize that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar appears to be null due to the bug, then your program will silently continue working incorrectly, which may be a greater disaster. This way an error may occur much later and it would be much harder to know at which point it went wrong.

Related questions

Browse Categories