Why did Java 8 introduce *Integer.sum(int a, int b)*

6.8k views Asked by At

I just noticed that JDK8 introduced this method for Integer class:

 /**
 * Adds two integers together as per the + operator.
 *
 * @param a the first operand
 * @param b the second operand
 * @return the sum of {@code a} and {@code b}
 * @see java.util.function.BinaryOperator
 * @since 1.8
 */
public static int sum(int a, int b) {
    return a + b;
}

What's the point of this method? Why should i call this method instead of using the + operator? The only possibility I can think of is that, for instance, when mixing strings and ints the + operator changes meaning, so

System.out.println("1"+2+3); // prints 123
System.out.println("1"+Integer.sum(2,3)); // prints 15

but using parenthesis would work anyway

System.out.println("1"+(2+3)); // prints 15
1

There are 1 answers

5
Eran On BEST ANSWER

It can be useful as a method reference (Integer::sum) passed to a method that requires a relevant functional interface (IntBinaryOperator).

For example :

int sum = IntStream.range(1,500).reduce(0,Integer::sum);

Of course, this example can use .sum() instead of reduce. I just noticed that the Javadoc for IntStream.sum mention this exact reduction as being equivalent to sum().