What is the Optional.orElse() method in Java?

In Java, the Optional object is a container object that may or may not contain a value. The Optional class is present in the java.util package.

You can read more about the Optional class here.

What is the orElse() method of the Optional class?

The orElse() method will return the value present in an Optional object. If the value is not present, then the passed argument is returned.

public T orElse(T other)

Argument

The argument is the value to be returned if the Optional object is empty, i.e., there is no value present in the Optional object.

Return value

If the Optional object contains a value, then that value is returned. Otherwise, the passed argument is returned.

Code

The code below shows how to use the orElse() method.

import java.util.Optional;
class OptionalOrElseExample {
public static void main(String[] args) {
Optional<Integer> optional1 = Optional.of(1);
System.out.println("Optional1 : " + optional1);
System.out.println("Value at Optional1 is : " + optional1.orElse(10));
Optional<Integer> optional2 = Optional.empty();
System.out.println("\nOptional2 : " + optional2);
System.out.println("Value at Optional2 is : " + optional2.orElse(10));
}
}

Explanation

In the code above:

  • In line 1, we imported the Optional class.
import java.util.Optional;
  • In line 5, we created an Optional object of type Integer with value 1 through the of() method.
Optional<Integer> optional1 = Optional.of(1);
  • In line 7, we called the orElse() method on the optional1 object with 10 as an argument. This method returns 1 because the optional1 object contains a value.
optional1.orElse(10); // 1 
  • In line 9, we used the empty() method to get an empty Optional object of the Integer type. The returned object doesn’t have any value.
Optional<Integer> optional2 = Optional.empty();
  • In line 11, we called the orElse() method on the optional2 object with 10 as an argument. This method returns 10 because the optional2 object doesn’t contain any value.
optional2.orElse(10); // 10

Free Resources