Java 25 (LTS) reference · Optional

Java Optional orElse() Method

Return the value if present, otherwise a default. orElseGet() computes the default lazily, only when needed.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

optional.orElse(other)

Parameters

ParameterDescription
other
T
The default value.

Return value

The value or the default.

Examples

A default value
import java.util.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Optional.of("dark").orElse("light"));
        System.out.println(Optional.<String>empty().orElse("light"));
    }
}

Output

dark
light

Run this on your computer — see “Get Started” for setup.

orElse() always evaluates its argument
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] calls = {0};
        Optional<String> present = Optional.of("cached");
        present.orElse(expensive(calls));            // runs expensive() even though a value is present
        present.orElseGet(() -> expensive(calls));  // doesn't run it
        System.out.println("expensive() ran " + calls[0] + " time(s)");
    }

    static String expensive(int[] calls) {
        calls[0]++;
        return "computed";
    }
}

Output

expensive() ran 1 time(s)

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?