This question has to be updated because it is marked as duplicated, but all the linked questions are not completely matching what is tried to be asked:
Is there a reason, that Optional.of(aNullableVar)
is required, as Optional.ofNullable(aNullableVar)
checks for null pointer inner the method?
As what Savior answered, a purpose may be like a guard clause:
Object object = getObject();
Optional.of(object);
System.out.println(object.toString());
It's equivalent to:
Object object = getObject();
Objects.requireNonNull(object);
System.out.println(object.toString());
and
Object object = getObject();
if (object == null) {
throw new NullPointerException();
}
System.out.println(object.toString());
Optional.of in Java 8:
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
Optional.ofNullable in Java 8:
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}