Optional.orElse()

Anil R
1 min readSep 30, 2024

--

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 the Optional.

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 the Optional.
  • Avoid Null Checks: It helps avoid null checks by providing a way to work with potentially empty values.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet