Java 8 Features Optional class

The Optional class is a feature introduced in Java 8 that provides a way to handle null values more effectively. It is a container object that may or may not contain a non-null value. The purpose of Optional is to provide a simple way to write code that works correctly even if a variable may be null.

The Optional class is defined in the java.util package and has the following characteristics:

1. It is a final class and cannot be extended.
2. It has two possible states: empty or containing a non-null value.
3. It provides several methods for working with the contained value, such as isPresent(), get(), orElse(), and orElseGet().

Here’s an example of how the Optional class can be used:

import java.util.Optional;

public class Example {
    public static void main(String[] args) {
        String str = null;
        Optional optionalStr = Optional.ofNullable(str);

        if (optionalStr.isPresent()) {
            System.out.println("String is present: " + optionalStr.get());
        } else {
            System.out.println("String is not present");
        }

        String defaultStr = optionalStr.orElse("default value");
        System.out.println("String value: " + defaultStr);
    }
}

In this example, we create an Optional object from a null value using the ofNullable() method. We then check whether the Optional contains a value using isPresent() and print out the value using get(). If the Optional is empty, we print a message stating that the value is not present.

We then use the orElse() method to provide a default value if the Optional is empty. In this case, the default value is “default value”. The orElse() method returns the contained value if it is present, or the default value if the Optional is empty.

The Optional class can be useful in situations where a method may return a null value, and the caller needs to handle that null value appropriately. By using Optional, the code can be written in a more concise and readable way, and null checks can be eliminated.