Using Objects.requireNonNullElse() where Optional not being able to be used.

Transcribed from the original LinkedIn image post.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/*
When returning a object that can have null value. wrapping it with an optional
can give you NullPointerException if object contains null.
In this case using optional might create some issue.
*/
import java.util.*;

public class Day03 {
    public static void main(String[] args) {
        // String fileExtension = getFileExtensionOpt().get();
        String fileExtension = Objects.requireNonNullElse(
            getFileExtension(),
            "got null in getFileExtension()"
        );
        System.out.println(fileExtension);
    }

    // will cause NullPointerException when get() is called on returned object
    public static Optional<String> getFileExtensionOpt() {
        return Optional.of(null);
    }

    // without optional
    public static String getFileExtension() {
        return null;
    }
}

The original LinkedIn graphic is preserved below.

Day 3 LinkedIn post