September 2019
Intermediate to advanced
816 pages
18h 47m
English
Confusing or mistakenly using Optional.of() instead of Optional.ofNullable(), or vice versa, can lead to weird behaviors and even NullPointerException.
Check the following failed attempt to write a snippet of code to avoid NullPointerException:
// Avoidpublic Optional<String> isbn(String bookId) { // the fetched "isbn" can be null for the given "bookId" String isbn = ...; return Optional.of(isbn); // this throws NPE if "isbn" is null :(}
But, most probably, we actually wanted to use ofNullable(), as follows:
// Preferpublic Optional<String> isbn(String bookId) { // the fetched "isbn" can be ...