Sum of an array elements in Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to sum up all the elements of an array.

Using Java Looping

package com.technicalkeeda.app;

public class SumOfArrayElements {
    public static void main(String args[]) {
        int[] elements = {1,2,3,4,5};
        int sum = 0;
        for (int element: elements) {
            sum = sum + element;
        }
        System.out.println("Sum of array elements is:- " + sum);
    }
}

output

Sum of array elements is:- 15

Using Java 8 Arrays.stream()

IntStream java.util.Arrays.stream(int[] array) returns a sequential IntStream with the specified array as its source.

int java.util.stream.IntStream.sum() method returns the sum of elements in this stream.

package com.technicalkeeda.app;
import java.util.Arrays;

public class SumOfArrayElements {
    public static void main(String args[]) {
        int[] elements = { 1, 2, 3, 4, 5 };

        int sum = Arrays.stream(elements).sum();

        System.out.println("Sum of array elements is:- " + sum);
    }
}

output

Sum of array elements is:- 15


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0350 seconds.