Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

util.OptionalLong: practical reference

util.OptionalLong: practical reference: OptionalLong stores one present primitive long or an empty state without boxing to Long.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

java.util.OptionalLong

OptionalLong stores one present primitive long or an empty state without boxing to Long.

Use it for optional counters, timestamps, or sizes when the entire long range remains valid data.

Do not treat empty as zero or call getAsLong without checking isPresent; absence causes NoSuchElementException.

orElseGet invokes its LongSupplier only when empty, ifPresentOrElse selects exactly one branch, and stream contains zero or one long.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var value = java.util.OptionalLong.empty();
        System.out.println(value.orElse(42));
    }
}

Result

42

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources