# How do you find the sum of all the numbers in an array in Java?

I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the `Math` class for this.

``````define a sum variable = 0

for each number in array:
sum = sum + number
``````

There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.

You just need to have a variable for the sum and loop through the array adding each value you find to the sum.

You can make your code look better like this:

``````public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
...
System.out.println("Result is " + sumOfNumbers(numbers));
}

private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
``````

You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.

If there were no integers, then the total is 0.

``````int sum = 0;

for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
``````

You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.

Just..

``````int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}

System.out.println(sum);
``````

There are two things to learn from this exercise :

You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop. You need to store the result of the summation in an accumulator. For this, you need to create a variable.

``````int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
``````

This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.

Other answers are perfectly fine, but here's one with some for-each syntactic sugar.

``````int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for (int i : someArray)
sum += i;
``````

Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.

``````class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
``````

The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.

``````int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;

for (int i : someArray)
sum += i;
``````
`````` public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}

//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}

//To display the sum
System.out.println("The sum is :"+sum);

}
}
``````