PROGRAMMING

NOTEBOOK

Optional class in Java?

Last updated: August 31, 2024
Author

Written By:

Gagandeep Singh

The Optional class in Java is used to represent a value that might be present or absent, essentially providing a container object which may or may not contain a non-null value. Here’s why it's useful:

Avoid NullPointerExceptions: It helps to avoid NullPointerExceptions by explicitly indicating the potential absence of a value. Instead of returning null from a method, you return an Optional, which makes the absence of a value explicit and encourages checking.

Better API Design: It makes API design cleaner and more expressive. By returning an Optional, you signal to the caller that the value might be absent and that they need to handle this case.

Encourages Functional Programming: Optional supports functional programming techniques such as mapping, filtering, and chaining operations, which can lead to more readable and concise code.

Reduces Boilerplate Code: It reduces boilerplate code that’s often required to check for null and handle default values.

Improves Readability: Code using Optional can be more readable and self-documenting, as it makes the possibility of absence explicit.

Here’s a simple example of how Optional can be used


import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        Optional<String> optionalValue = getOptionalValue(true);

        // Using ifPresent to handle the case where the value is present
        optionalValue.ifPresent(value -> System.out.println("Value is: " + value));

        // Using orElse to provide a default value when the optional is empty
        String value = optionalValue.orElse("Default Value");
        System.out.println("Value or default: " + value);
    }

    public static Optional<String> getOptionalValue(boolean isPresent) {
        if (isPresent) {
            return Optional.of("Actual Value");
        } else {
            return Optional.empty();
        }
    }
}