java array sum code example

Example 1: sum of all numbers in array java

int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);

Example 2: sum numbers in array java

public class Exercise2 {
public static void main(String[] args) {      
int my_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

for (int i : my_array)
    sum += i;
System.out.println("The sum is " + sum);
}
}

Example 3: how to add up all numbers in an array

var numbers = [10, 20, 30, 40] 
var sum = 0;
for (var i = 0; i < numbers.length; i++) {  sum += numbers[i]}

Example 4: arrays.sum

int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();