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.
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)
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.
If the Optional
object contains a value, then that value is returned. Otherwise, the passed argument is returned.
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));}}
In the code above:
Optional
class.import java.util.Optional;
Optional
object of type Integer
with value 1
through the of()
method.Optional<Integer> optional1 = Optional.of(1);
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
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();
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