It depends. How many numbers are you adding? Testing many of the above suggestions:
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);
public static long sumParallel(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).parallel().reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStream(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumLoop(int[] array) {
final long start = System.nanoTime();
int sum = 0;
for (int v: array) {
sum += v;
}
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumArray(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array) .sum();
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStat(int[] array) {
final long start = System.nanoTime();
int sum = 0;
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static void test(int[] nums) {
System.out.println("------");
System.out.println(FORMAT.format(nums.length) + " numbers");
long p = sumParallel(nums);
System.out.println("parallel " + FORMAT.format(p));
long s = sumStream(nums);
System.out.println("stream " + FORMAT.format(s));
long ar = sumArray(nums);
System.out.println("arrays " + FORMAT.format(ar));
long lp = sumLoop(nums);
System.out.println("loop " + FORMAT.format(lp));
}
public static void testNumbers(int howmany) {
int[] nums = new int[howmany];
for (int i =0; i < nums.length;i++) {
nums[i] = (i + 1)%100;
}
test(nums);
}
public static void main(String[] args) {
testNumbers(3);
testNumbers(300);
testNumbers(3000);
testNumbers(30000);
testNumbers(300000);
testNumbers(3000000);
testNumbers(30000000);
testNumbers(300000000);
}
}
I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you’re running:
------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436
It might be too late, but I see that many solutions posted here use O(n^2) time complexity, this is okay for small inputs, but as you go ahead with large inputs, you might want to reduce time complexity. Here is something which I worked on to do the same in linear time complexity.
NOTE : The second solution posted by Arunkumar is constant time complexity.
private int getDigits(int num) {
int sum =0;
while(num > 0) { //num consists of 2 digits max, hence O(1) operation
sum = sum + num % 10;
num = num / 10;
}
return sum;
}
public int addDigits(int N) {
int temp1=0, temp2= 0;
while(N > 0) {
temp1= N % 10;
temp2= temp1 + temp2;
temp2= getDigits(temp2); // this is O(1) operation
N = N/ 10;
}
return temp2;
}
Please ignore my variable naming convention, I know it is not ideal. Let me explain the code with sample input , e.g. «12345». Output must be 6, in a single traversal.
Basically what I am doing is that I go from LSB to MSB , and add digits of the sum found, in every iteration.
The values look like this
Initially temp1 = temp2 = 0
N | temp1 ( N % 10) | temp2 ( temp1 + temp2 )
12345 | 5 | 5
1234 | 4 | 5 + 4 = 9 ( getDigits(9) = 9)
123 | 3 | 9 + 3 = 12 = 3 (getDigits(12) =3 )
12 | 2 | 3 + 2 = 5 (getDigits(5) = 5)
1 | 1 | 5 + 1 = 6 (getDigits(6) = 6 )
Answer is 6, and we avoided one extra loop.
I hope it helps.
In this section, we will create Java programs to find the sum or addition of two numbers using the method and command-line arguments, the sum of three numbers, and the sum of n numbers.
Sum of Two Numbers in Java
In Java, finding the sum of two or more numbers is very easy. First, declare and initialize two variables to be added. Another variable to store the sum of numbers. Apply mathematical operator (+) between the declared variable and store the result. The following program calculates and prints the sum of two numbers.
SumOfNumbers1.java
Output:
The sum of numbers is: 340
Sum of Two Numbers in Java Using Method
There are two ways to find the sum of two numbers in Java.
- By using User-defined Method
- By using sum() Method
By Using User-defined Method
The Java Scanner class allows us to read input from the user. We take two numbers as input and pass them to the user-defined method sum(). The following program calculates the sum of two numbers using the method and prints the result.
SumOfNumbers2.java
Output:
Enter the first number: 34 Enter the second number: 12 The sum of two numbers x and y is: 46
By Using Integer.sum() Method
The Integer class provides the sum() method. It is a static method that adds two integers together as per the + operator. It can be overloaded and accepts the arguments in int, double, float, and long.
Syntax:
It returns the sum of the numbers that are passed as an argument. It throws ArithmaticException when the result overflows an integer value.
Note: If both arguments are negative, the result will be negative.
SumOfNumbers3.java
Output:
The sum of x and y is: 88 The sum of x and y is: -38
Similarly, we can calculate the sum of double, float, and long type numbers.
Sum of Two Numbers Using Command Line Arguments in Java
The command-line arguments are passed to the program at run-time. Passing command-line arguments in a Java program is quite easy. They are stored as strings in the String array passed to the args[] parameter of the main() method in Java.
SumOfNumbers4.java
Output:
The sum of x and y is: 101
First, compile the above program by using the command javac SumOfNumbers4.java. After that, run the program by using the command java SumOfNumbers4 89 12. Where 89 and 12 are command-line arguments.
Sum of Three Numbers in Java
The program for the sum of three numbers is the same as the sum of two numbers except there are three variables.
SumOfNumbers5.java
Output:
Enter the first number: 12 Enter the second number: 34 Enter the third number: 99 The sum of three numbers x, y, and z is: 145
Sum of N Numbers in Java
- Read or initialize an integer N (number of integers to add).
- Run a loop up to N times that ask to provide integers (to be added) again and again.
- Calculate the cumulative sum for each input and store it into a variable (sum).
- After terminating the loop, print the result.
Let’s implement the above steps in a Java program.
SumOfNumbers6.java
Output:
Enter Number of Numbers to be Calculated: 4 Enter the number: 12 Enter the number: 13 Enter the number: 5 Enter the number: 4 The sum of the numbers is: 34
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
The java.lang.Integer.sum() is a built-in method in java that 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)
Parameter: The method accepts two parameters that are to be added with each other: a : the first integer value. b : the second integer value.
Return Value: The method returns the sum of its arguments.
Exception: The method throws an ArithmeticException when the result overflows an int.
Examples:
Input: a = 170, b = 455 Output: 625 Input: a = 45, b = 45 Output: 90
Below programs illustrate the Java.lang.Integer.sum() method:
Program 1: For a positive number.
java
import
java.lang.*;
public
class
Geeks {
public
static
void
main(String[] args)
{
int
a =
62
;
int
b =
18
;
System.out.println(
"The sum is ="
+ Integer.sum(a, b));
}
}
Program 2: Below program illustrates the exception.
java
import
java.lang.*;
public
class
Geeks {
public
static
void
main(String[] args)
{
int
a =
92374612162
;
int
b =
181
;
System.out.println(
"The sum is ="
+ Integer.sum(a, b));
}
}
Output:
prog.java:8: error: integer number too large: 92374612162 int a = 92374612162; ^ 1 error
Program 3 : Find the sum of integers using a loop
Java
import
java.io.*;
public
class
Arrays {
public
static
void
main(String[] args)
{
int
[] arr = {
2
,
4
,
6
,
8
,
10
};
int
sum =
0
;
for
(
int
i =
0
; i < arr.length; i++) {
sum += arr[i];
}
System.out.println(
"Sum of array elements is: "
+ sum);
}
}
Output
Sum of array elements is: 30
Last Updated :
03 Apr, 2023
Like Article
Save Article
Every now and then, I need to do some basic stuff in Java and I wonder what is the best way to this. This happened to me a few days ago! I needed to simply get the sum of a List of numbers and I found out there are a number of ways — pun intended — to do this.
The old-fashioned approach
We can create a simple loop to do this. I am using Java 11 so, forgive me if you are using, for example, Java 8, and the List.of
and var
does not work in your case. Nonetheless, I believe you’ll still get the point.
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = 0;
for (int i = 0; i < listOfNumbers.size() ; i++) {
sum += listOfNumbers.get(i);
}
Obviously, since Java 5, we have enhancements for loops so, I can rewrite the same code like this.
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = 0;
for (int number : listOfNumbers) {
sum += number;
}
The difference is subtle. However, it is already more expressive as it says something like «of each number
coming from listOfNumbers
I want to do the following …».
The Java Stream approach
People who know me, know that I was brainwashed, during my university days, with programming in Haskell. This means I have a lot of love for pure functional programming. Not that Java can handle that ?, but the expressiveness of functional programming is somewhat available using the stream API.
With the stream API in Java, we can execute the MapReduce programming model. For the issue I am trying to solve here, I do not need to map as the numbers will stay as they are. I do, however, have to reduce the List into a single number, the sum.
Collect
In probably 99% of the cases, we use the collect function with the standard toList()
collector to reduce our stream back into a List.Similar to this:
var time2ToList = listOfNumbers.stream()
.map(i -> i * 2)
.collect(Collectors.toList());
However, there is more to life than collecting a stream back into a List. Browsing the Collectors library you can find functions like summingInt()
, summingDouble()
and summingLong()
.You can use these functions to collect (or reduce) the List into the sum.
The summmingInt function does require a function that turns the input you have into an int
. In this case, I can simply use «identity function». The functioni -> i
will be sufficient.
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = listOfNumbers.stream()
.collect(Collectors.summingInt(i -> i));
This identity function might look silly so, you can use Integer.intValue()
instead.
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = listOfNumbers.stream()
.collect(Collectors.summingInt(Integer::intValue));
When I do this, my IDE—IntelliJ IDEA in my case—advises me to refactor this and use the mapToInt()
function like seen below:
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = listOfNumbers.stream()
.mapToInt(Integer::intValue).sum();
Technically what we do here is mapping every item to an int, what it already is ¯(ã)/¯ right, and reduce it with the sum() function.
It gets more clear if you look at the inferred types. You simply cannot have a List of primitives. So, the List is a list of Integer
(the Object). This means that every item in the list needs to get back to the primitive int
to make the sum()
possible. The previous example with the identity function in the collector works because of Java unboxing.
If you prefer using primitive Lists in Java, I suggest taking a look at the Eclipse Collections library.
Reduce
Reduction in Java is achieved by a couple of function in the stream API.In addition to collect()
, there is also the obviously-named function reduce()
.
var listOfNumbers = List.of(1,2,3,4,5,6,7,8,9,10);
var sum = listOfNumbers.stream()
.reduce(0 , (num1, num2) -> num1 + num2);
The reduce function in this case takes a starting point and BiFunction
lambda expression. The BiFunction is applied to the starting point and the first number,he result of the function is applied to the second number, and so on.
The code above does something like this:0 + 11 + 23 + 36 + 4etc …
Now, you can omit the starting point 0
. However, the reduce function will return an Optional
in this case as the List it tries to reduce might be empty.
Conclusion
As you can see, there are multiple ways to solve this problem. Without any doubt, people will come up with even more exotic ways to solve this. My personal favorite is the reduce()
option. For me, this is the most expressive and pure solution in Java. I simply want to reduce a list to a single number and don’t need to care of the transformations from boxed types to primitives. Furthermore, I can reuse this approach when I need to reduce a List of other types by writing a reduction lambda function that fits my needs.