In Spring (and Java in general), Optional
is a container object that may or may not contain a non-null value. The orElse()
method is used to return the value if present, or a default value if the Optional
is empty.
Here’s how Optional.orElse()
works:
Syntax:
public T orElse(T other)
Parameters:
other
- the value to be returned if there's no value present in theOptional
.
Returns:
- The contained value if present, otherwise the default value provided.
Example:
import java.util.Optional;
public class OptionalExample {
public static void main(String[] args) {
Optional<String> optionalWithValue = Optional.of("Hello, World!");
Optional<String> emptyOptional = Optional.empty();
// Using orElse() to provide a default value if the Optional is empty
String value1 = optionalWithValue.orElse("Default Value");
String value2 = emptyOptional.orElse("Default Value");
System.out.println(value1); // Outputs: Hello, World!
System.out.println(value2); // Outputs: Default Value
}
}
Key Use Cases:
- Non-nullable Values: You can use
orElse()
when you want to return a default value if no value is present inside theOptional
. - Avoid Null Checks: It helps avoid
null
checks by providing a way to work with potentially empty values.