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.
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.
public double orElse(double other)
orElse
takes the double
value that is to be returned if the OptionalDouble
object is OptionalDouble
object
If the OptionalDouble
object contains a double
value, then orElse
returns the value; otherwise, it returns the passed argument.
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));}}
In the code above:
OptionalDouble
class.import java.util.OptionalDouble;
of
method to create an OptionalDouble
object with the double
value 1.5
.OptionalDouble optional1 = OptionalDouble.of(1.5);
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
empty
method to get an empty OptionalDouble
object. The returned object doesn’t have any value.OptionalDouble optional2 = OptionalDouble.empty();
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