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
Integer sum() Method in Java sum() is a built-in method in java which returns the sum of its arguments. The method adds two integers together as per the + operator. Syntax : public static int sum(int a, int b)
In Java, integer addition and double addition use different hardware. Even though they may seem the same to you, they are actually quite different to the computer. The computer wants to either add two int values or two double values. Java's solution (as in many other languages) is type promotion.
Java Integer sum() Method. The sum() method of Java Integer class numerically returns the sum of its arguments specified by a user. This method adds two integers together as per the + operator. It can be overloaded and accepts the arguments in int, double, float and long.
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.
Numeric value entered by a user. The sum () method returns the sum of its method arguments which will be specified by a user. ArithmeticException: It throws exception when the result overflows an integer value. // It will return the sum of a and b.
Using Collectors.summingInt () Another way to add the list of integers is using the summingInt () of Collectors api. In the similar to the summingInt (), there are separate methods to deal with the addition of long and double such as summingDouble () and summingLong ().
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With