Java Optional Class in the java.util Package

Optional is a class added in Java 8. The Optional class is useful when handling null, so let us look at its basic usage.

What Is Optional?

Optional is used when you want to explicitly indicate that a method may return null as its return value. By showing that a method can return null, it helps you implement programs that use that method more safely.

How to Declare Optional

To use Optional, wrap the type.

Optional<String> optional;

It can also be used with classes you create.

import java.math.BigDecimal;

public class Foo {
    private String str;
    private BigDecimal value;
}
Optional<Foo> opt;

Creating Optional Instances

The Optional class provides static methods for creating instances, so use these methods to create them.

  • Optional.empty() : Creates an Optional instance whose value is null.
  • Optional.of(value) : Creates an Optional instance for the argument value.
  • Optional.ofNullable(value) : If the argument value is null, it is empty; if it is not null, the result is the same as the of method.

Optional.of can be declared as follows.

Optional<String> opt1 = Optional.of("test");

Be careful because Optional.of throws java.lang.NullPointerException when the argument is null.

Optional<String> opt1 = Optional.of(null);

For this reason, Optional.ofNullable is commonly used.

Optional<String> opt1 = Optional.ofNullable("test");
Optional<String> opt2 = Optional.ofNullable(null);

Foo test = new Foo();
Optional<Foo> opt3 = Optional.ofNullable(test);

How to Use Optional Return Methods

Let us look at Optional return methods.

How to Use the or Method

The or method executes processing only when the object specified as the argument of the Optional.ofNullable method is null.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        System.out.println(value.or(() -> Optional.of("null입니다.")).get());
    }
}

Execution result:

null입니다.

How to Use the orElse Method

If the argument of the Optional.ofNullable method is null, the value passed to the orElse method is returned. If it is not null, the non-null value is returned.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        str = value.orElse("null입니다.");
        System.out.println(str);
    }
}

Execution result:

null입니다.

How to Use the orElseGet Method

If the argument of the Optional.ofNullable method is null, the result of the supplier passed to the orElseGet method is returned. If it is not null, the non-null value is returned.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        str = value.orElseGet(Sample::getDefaultValue);
        System.out.println(str);
    }
    
    private static String getDefaultValue(){
        return "Default 입니다.";
    }
}

The execution result is as follows.

Default 입니다.

How to Use the orElseThrow Method

The orElseThrow method behaves differently depending on whether it has an argument. If it has no argument, it throws NoSuchElementException when the value is null, and returns the value when it is not null.

import java.util.NoSuchElementException;
import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        try {
            str = value.orElseThrow();
            System.out.println(str);
        } catch (NoSuchElementException ex) {
            System.out.println("null입니다.");
        }
    }
}

Execution result:

null입니다.

When there is an argument, you can specify an exception class object through throw.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        try {
            System.out.println(value.orElseThrow(() -> new RuntimeException()));
        } catch (RuntimeException e) {
            System.out.println("null입니다.");
        }    
    }
}

Execution result:

null입니다.

How to Use the ifPresent Method

Executes the operation specified in the argument only when the value is not null.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        value.ifPresent(System.out::println);
    }
}

When this is executed, nothing is processed because str is null.

How to Use the ifPresentOrElse Method

You can also perform processing when the value is null. Specify the processing for the non-null case as the first argument, and the processing for the null case as the second argument.

import java.util.Optional;

public class Sample {
    public static void main(String[] args) {
        String str = null;
        Optional<String> value = Optional.ofNullable(str);
        value.ifPresentOrElse(
            System.out::println, 
            () -> System.out.println("null입니다"));
    }
}

Execution result:

null입니다.