Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

OptionalDouble: fallback or value retrieval

OptionalDouble represents a double value or its absence. Learn how orElse differs from getAsDouble.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

double orElse(double other)
double getAsDouble()

OptionalDouble holds a double value or is empty. Create these states with OptionalDouble.of(value) and OptionalDouble.empty(). The reference itself should not be null.

OptionalDouble.orElse(other) returns the stored value, or other when empty. OptionalDouble.getAsDouble() returns the value but throws NoSuchElementException when empty.

Choose orElse when a fallback is acceptable. Ensure a value exists before using getAsDouble(). The Java SE 21 documentation prefers orElseThrow() over getAsDouble().

Examples

import java.util.NoSuchElementException;
import java.util.OptionalDouble;

public class Main {
    public static void main(String[] args) {
        OptionalDouble present = OptionalDouble.of(2.5);
        OptionalDouble empty = OptionalDouble.empty();

        System.out.println(present.orElse(1.0));
        System.out.println(empty.orElse(1.0));
        System.out.println(present.getAsDouble());
        try {
            empty.getAsDouble();
        } catch (NoSuchElementException exception) {
            System.out.println("NoSuchElementException");
        }
    }
}

Result

2.5
1.0
2.5
NoSuchElementException

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources