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?
What is the ofNullable() method of the Optional class? The ofNullable() method is used to get an instance of the Optional class with a specified value. If the value is null , then an empty Optional object is returned.
In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional class forces you to think about the case when the value is not present.
The of() method of java. util. Optional class in Java is used to get an instance of this Optional class with the specified value of the specified type. Parameters: This method accepts value as parameter of type T to create an Optional instance with this value.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With