Java Optional orElse() Method Example

In this source code example, we will demonstrate how to get the default value using the Optional orElse() method with an example.

The orElse() method returns the value if present, otherwise return other (default value).

Java Optional orElse() Method Example

In the below example, orElse() method return default value because Optional contains null value:

import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional = stringOptional.orElse("default@gmail.com");
        System.out.println(defaultOptional);
    }
}
Output:
default@gmail.com
In the below example, orElse() method return actual value because Optional contains actual value:
import java.util.Optional;

public class OptionalDemo {
    public static void main(String[] args) {

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional = stringOptional.orElse("default@gmail.com");
        System.out.println(defaultOptional);
    }
}
Output:
ramesh@gmail.com

Related Optional Class Method Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course