Skip to content

Java Optional class

A container that may or may not hold a valuable gem. Optionals allow us to represent situations where a value may be present or absent, helping us avoid those dreaded NullPointerExceptions and adding clarity to our code.

java
import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) {
        Optional<String> optionalName = Optional.of("John");

        // Check if the value is present
        if (optionalName.isPresent()) {
            System.out.println("Hello, " + optionalName.get() + "!");
        } else {
            System.out.println("Hello, anonymous!");
        }
    }
}

In our example, we create an Optional object called optionalName containing the value "John". We then use the isPresent() method to check if the value is present. If it is, we greet the user with a personalized message. If not, we greet them as an anonymous user.

But wait, there's more! Optionals offer a range of methods to work with, making it easy to perform actions based on whether a value is present or not. For example, we can use the orElse() method to provide a default value if the Optional is empty:

java
public class OptionalExample {
    public static void main(String[] args) {
        Optional<String> optionalName = Optional.empty();

        // Use orElse() to provide a default value
        String name = optionalName.orElse("Anonymous");
        System.out.println("Hello, " + name + "!");
    }
}

But wait, there's more to Optionals than just checking for presence! They offer a range of methods to help us safely interact with values, such as orElse(), orElseGet(), and orElseThrow(), allowing us to handle absent values gracefully without resorting to messy null checks.

orElseThrow

java
import java.util.Optional;

public class OrElseThrowExample {
    public static void main(String[] args) {
        Optional<String> treasure = Optional.empty();

        try {
            String foundTreasure = treasure.orElseThrow(() -> new RuntimeException("Oops! Treasure not found!"));
            System.out.println("Congratulations! You found the " + foundTreasure + "!");
        } catch (RuntimeException e) {
            System.out.println(e.getMessage());
        }
    }
}

In this example, we create an empty Optional called treasure. We then use the orElseThrow() method to specify that if the Optional is empty, we want to throw a RuntimeException with the message "Oops! Treasure not found!". Since the Optional is indeed empty, the specified exception is thrown, and we gracefully handle it by catching and printing the error message.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.