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
}
}

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
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!