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.

0 votes

`Math`

class for this.

0 votes

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.

0 votes

You can make your code look better like this:

```
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
```

0 votes

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.

0 votes

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);
```

0 votes

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];
}
```

0 votes

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);
}
}
```

...