Sobes.tech
Junior — Middle

How does the Optional class help prevent NullPointerException in code?

sobes.tech AI

Answer from AI

The Optional class in Java serves as a container that may hold a value or be empty (null). Using Optional helps explicitly indicate that a value might be absent, which forces the developer to handle this case explicitly rather than risking an unexpected NullPointerException.

For example, instead of returning null from a method, you can return Optional.empty(), and when a value is present — Optional.of(value). This allows the use of methods like isPresent(), orElse(), ifPresent(), and others for safe handling of the potential absence of a value.

Example:

Optional<String> getName(boolean hasName) {
    if (hasName) {
        return Optional.of("Ivan");
    } else {
        return Optional.empty();
    }
}

Optional<String> name = getName(false);
name.ifPresent(n -> System.out.println(n)); // will not print anything, no NPE
String defaultName = name.orElse("Guest");
System.out.println(defaultName); // will print "Guest"

Thus, Optional forces explicit handling of the absence of a value, reducing the risk of NullPointerException."}]}]}

How does the Optional class help prevent… - sobes.tech