How to set a Default Value for Optional is Empty or Null in Java


The Object class from the java.util package is a container object that may or may not contain a non-null value. If a value is present then the isPresent() method returns true.

If you want to set a default value for the Optional object, then you can make use of the orElse() method with a default value passed as an argument to it.

Let's take a look at an example.

import java.util.Optional;

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

        Optional<String> optionalWithValue = Optional.of("Mike");
        Optional<String> optionalEmpty = Optional.empty(); // empty
        Optional<String> optionalNull = Optional.ofNullable(null); // null

        String value1 = optionalWithValue.orElse("No Name");
        String value2 = optionalEmpty.orElse("Default Value");
        String value3 = optionalNull.orElse("0");

        System.out.println("Value 1: " + value1); // Output: Value 1: Mike
        System.out.println("Value 2: " + value2); // Output: Value 2: Default Value
        System.out.println("Value 3: " + value3); // Output: Value 3: 0
    }
    
}
Output

Reference:

- https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Optional.html#orElse(T)

public T orElse(T other)

If a value is present, return the value, otherwise, return the other.

Parameters:
other - the value to be returned, if no value is present. May be null.

Returns:
the value, if present, otherwise other

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap