Course contentsShow
← Java
Lesson 1770 of 2,87037. Optional for Null SafetyFree lesson

Primitive Optionals: OptionalInt, OptionalLong, OptionalDouble

Discover specialized Optional types for primitives that avoid boxing overhead in numeric contexts.

Primitive Optionals: OptionalInt, OptionalLong, OptionalDouble

What you'll learn: How to use specialized Optional types for primitives that avoid unnecessary boxing overhead.

The Boxing Problem with Regular Optional

Remember how primitive specializations exist to avoid boxing overhead? The same principle applies to Optional. When you use Optional<Integer>, every int value gets boxed into an Integer object. For numeric operations, this creates unnecessary object allocation and garbage collection pressure.

Meet the Primitive Optionals

Java provides three specialized Optional types for primitives:

  • OptionalInt – for int values
  • OptionalLong – for long values
  • OptionalDouble – for double values

These work exactly like Optional, but they hold primitive values directly without boxing.

Creating Primitive Optionals

OptionalInt emptyInt = OptionalInt.empty();
OptionalInt presentInt = OptionalInt.of(42);

OptionalLong emptyLong = OptionalLong.empty();
OptionalLong presentLong = OptionalLong.of(1000L);

OptionalDouble emptyDouble = OptionalDouble.empty();
OptionalDouble presentDouble = OptionalDouble.of(3.14);

Notice there's no ofNullable() method – primitives can't be null, so it's not needed.

Retrieving Values

OptionalInt opt = OptionalInt.of(100);

int value = opt.getAsInt();      // throws if empty
int orElse = opt.orElse(0);      // returns 0 if empty
int orElseGet = opt.orElseGet(() -> 50);  // uses IntSupplier

The method names differ slightly (getAsInt(), getAsLong(), getAsDouble()) to match the primitive type.

Why Use Them?

In numeric contexts—especially with streams of primitives—using OptionalInt instead of Optional<Integer> eliminates boxing overhead, improving both performance and memory efficiency.

Key Takeaway: Use OptionalInt, OptionalLong, and OptionalDouble when working with primitives to avoid boxing overhead; they provide the same safety as Optional with better performance for numeric values.