Course contentsShow
← Java
Lesson 1697 of 2,87035. Functional InterfacesFree lesson

IntBinaryOperator, LongBinaryOperator, and DoubleBinaryOperator

Perform binary operations on primitives efficiently with specialized binary operators.

IntBinaryOperator, LongBinaryOperator, and DoubleBinaryOperator

What you'll learn: How to perform efficient binary operations on primitive numbers without boxing overhead.

The Problem These Solve

You've seen BinaryOperator<T> for combining two values of the same type. When working with primitives like int, long, or double, using BinaryOperator<Integer> forces Java to box and unbox values repeatedly—wrapping primitives in objects and unwrapping them. This creates performance overhead, especially in tight loops or stream operations.

The Primitive-Specialized Alternatives

Java provides three specialized interfaces for primitive binary operations:

  • IntBinaryOperator – takes two int parameters, returns int
  • LongBinaryOperator – takes two long parameters, returns long
  • DoubleBinaryOperator – takes two double parameters, returns double

Each has a single abstract method called applyAsInt, applyAsLong, or applyAsDouble respectively.

Why This Matters

Think of it like calculating totals in a cash register. Using BinaryOperator<Integer> is like converting each coin to a certificate, doing math on paper certificates, then converting back to coins. The primitive versions work directly with the coins—much faster.

Usage Example

IntBinaryOperator multiply = (a, b) -> a * b;
int result = multiply.applyAsInt(5, 7); // 35

DoubleBinaryOperator average = (a, b) -> (a + b) / 2.0;
double avg = average.applyAsDouble(10.5, 20.5); // 15.5

LongBinaryOperator max = (a, b) -> a > b ? a : b;
long maximum = max.applyAsLong(1000L, 2000L); // 2000

These are especially useful in reduction operations on primitive streams, where they eliminate boxing entirely.

Key Takeaway: Use IntBinaryOperator, LongBinaryOperator, and DoubleBinaryOperator when combining two primitive values of the same type to avoid boxing overhead and improve performance.