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 OptionalDouble object
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
OptionalDoubleclass.
import java.util.OptionalDouble;
- In line 5, we use the
ofmethod to create anOptionalDoubleobject with thedoublevalue1.5.
OptionalDouble optional1 = OptionalDouble.of(1.5);
- In line 7, we call the
orElsemethod on theoptional1object with111.11as an argument. This method returns1.5because theoptional1object already contains a double value.
optional1.orElse(111.11); // 1.5
- In line 9, we use the
emptymethod to get an emptyOptionalDoubleobject. The returned object doesn’t have any value.
OptionalDouble optional2 = OptionalDouble.empty();
- In line 11, we call the
orElsemethod on theoptional2object with111.11as an argument. This method returns111.11because theoptional2object doesn’t contain any value.
optional2.orElse(111.11); //111.11