The conceptual difference between choosing one over the other is explained in their documentation. He relies on the consumer API approach to choose which one should be used effectively by them.
Optional is a container object that may or may not contain a non-zero value.
A variable whose type is Optional should never be null ; This should always point to an Optional instance.
This is a value based class; the use of identification sensitive operations (including referential equality (==), an identifier hash code, or synchronization) on instances of the Optional may have unpredictable results and should be avoided.
ofNullable
returns Optional with the current value if the specified value is not null, otherwise empty Optional
orElse
returns a value, if present otherwise, returns another .
The following behavior follows:
String foo = null; => Optional.ofNullable(foo).orElse("nonNull") => Optional.ofNullable(null).orElse("nonNull") => Optional.empty().orElse("nonNull") => return otherwise "nonNull"
same as traverses
String foo = null, bar = null; => Optional.ofNullable(foo).orElse(bar); => Optional.ofNullable(null).orElse(bar); => Optional.empty().orElse(bar) => return otherwise 'bar' => returns null
Objects - a class consisting of static utility methods for working on objects or checking certain conditions before an operation.
These utilities include null or null-tolerant methods for calculating the hash code of an object, returning a string for the object, comparing two objects, and checking whether indexes or sub-ranges are values out of bounds.
Therefore, the difference in behavior:
String foo = null; => Objects.requireNonNullElse(foo, "nonNull") => Objects.requireNonNullElse(null, "nonNull");
which further evaluates internally if requireNonNull("nonNull", "defaultObj") and then
=> returns "nonNull" since its a non-null value
now that he crosses
String foo = null, bar = null; => Objects.requireNonNullElse(foo, bar); => Objects.requireNonNullElse(null, bar);
It checks internally if requireNonNull(bar, "defaultObj") , which then
=> throws a NullPointerException
As indicated also
throws NullPointerException - if both obj null and defaultObj null