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
It can be useful as a method reference (
Integer::sum
) passed to a method that requires a relevant functional interface (IntBinaryOperator
).For example :
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().