What is the OptionalDouble.orElse method in Java?

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

What is the orElse method of the OptionalDouble class?

The orElse method returns the double value present in the OptionalDouble object. If the value is not present, then orElse returns the passed argument.

Syntax

public double orElse(double other)

Parameters

orElse takes the double value that is to be returned if the OptionalDouble object is emptythere is no value present in the OptionalDouble object as an argument.

Return value

If the OptionalDouble object contains a double value, then orElse returns the value; otherwise, it returns the passed argument.

Code

The code below denotes how to use the orElse method.

import java.util.OptionalDouble;
class OptionalDoubleOrElseExample {
public static void main(String[] args) {
OptionalDouble optional1 = OptionalDouble.of(1.5);
System.out.println("Optional1 : " + optional1);
System.out.println("Double Value at Optional1 is : " + optional1.orElse(111.11));
OptionalDouble optional2 = OptionalDouble.empty();
System.out.println("\nOptional2 : " + optional2);
System.out.println("Double value at Optional2 is : " + optional2.orElse(111.11));
}
}

Explanation

In the code above:

  • In line 1, we import the OptionalDouble class.
import java.util.OptionalDouble;
  • In line 5, we use the of method to create an OptionalDouble object with the double value 1.5.
OptionalDouble optional1 = OptionalDouble.of(1.5);
  • In line 7, we call the orElse method on the optional1 object with 111.11 as an argument. This method returns 1.5 because the optional1 object already contains a double value.
optional1.orElse(111.11); // 1.5
  • In line 9, we use the empty method to get an empty OptionalDouble object. The returned object doesn’t have any value.
OptionalDouble optional2 = OptionalDouble.empty();
  • In line 11, we call the orElse method on the optional2 object with 111.11 as an argument. This method returns 111.11 because the optional2 object doesn’t contain any value.
optional2.orElse(111.11); //111.11