sum of all numbers in array java

https://‮‬www.lautturi.com
sum of all numbers in array java

To find the sum of all the numbers in an array in Java, you can iterate over the elements of the array and add them together using a loop.

Here's an example of how to find the sum of all the numbers in an array of int values:

int[] array = {1, 2, 3, 4, 5};
int sum = 0;
for (int i : array) {
    sum += i;
}
System.out.println(sum);  // prints 15

In this example, we're using a for-each loop to iterate over the elements of the array and add them to the sum variable. The output will be the sum of the elements of the array: 15.

You can also use the stream API introduced in Java 8 to find the sum of all the numbers in an array. Here's an example of how to do this:

int[] array = {1, 2, 3, 4, 5};
int sum = Arrays.stream(array).sum();
System.out.println(sum);  // prints 15

In this example, we're using the stream method of the Arrays class to create a stream of int values, and the sum method to sum the elements of the stream.

You can find more information about the stream API and examples of how to use it in the Java documentation.

Created Time:2017-10-17 20:18:56  Author:lautturi