Search code examples
javanulloption-type

Why Optional.isEmpty() which checks for NULL is not called isNull()


This might be a silly question.

When I am using Optional.isEmpty() like below in the code

Optional<List<String>> optional = Optional.of(new ArrayList<>());

optional.isEmpty(); // only checks if the value is NULL or not.

isEmpty() method is only checking whether the value null or not.

public boolean isEmpty() {
    return value == null;
}

This method name seems not clear for me.

I'm wondering why this method is named isEmpty() and not isNull() since it performs null-check under the hood?


Solution

  • This is the definition of Optional:

    A container object which may or may not contain a non-null value.

    Since the object itself is a container, which may or may not hold a value, isEmpty (or isPresent) refers to the status of the container, whether it holds something or not.

    isNull as a name would suggest that the Optional would be null, which would be a false impression, because the Optional itself is a properly existing instance.

    Is the Optional null if it does not hold a not-null value? No, you can check for

    myOptional == null
    

    and you will see it's false (you couldn't even call isEmpty otherwise). Is the object inside the container null? If isEmpty is null, then it's a sure thing. Hence, the Optional is either empty, or something is present inside of it.