Java 9 introduces the requireNonNullElse
and requireNonNullElseGet
methods to the Objects
class. Are these functionally any different to the Optional.ofNullable()
orElse()
and orElseGet()
methods?
String foo = null;
Objects.requireNonNullElse(foo, "nonNull");//returns the string "nonNull"
Optional.ofNullable(foo).orElse("nonNull");//also returns the string "nonNull"
If they have no functional difference, why was the Objects
one added now?
There is one minor difference in their behavior. Objects.requireNonNullElse()
requires that one of the parameters be non-null, otherwise, a NullPointerException
is thrown.
String foo = null, bar = null;
Optional.ofNullable(foo).orElse(bar); //returns a null value
Objects.requireNonNullElse(foo, bar); //throws a NullPointerException