SwadhyAI Notes

All Java notes

How to Find Sum of Array Elements in Java

The Challenge

Calculate the sum of all elements in an array!

Solutions

Method 1: Using For Loop

java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;

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

System.out.println("Sum: " + sum);
// Output: Sum: 15

Method 2: Using Enhanced For Loop

java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;

for (int num : numbers) {
    sum += num;
}

System.out.println("Sum: " + sum);
// Output: Sum: 15

Method 3: Using Java 8 Streams

java
import java.util.Arrays;

int[] numbers = {1, 2, 3, 4, 5};
int sum = Arrays.stream(numbers).sum();

System.out.println("Sum: " + sum);
// Output: Sum: 15

Did You Know?

Java 8 streams provide a clean, functional way to process arrays. The sum() method is optimized for performance!

Pro Tip

For large arrays, streams can be parallelized for better performance: Arrays.stream(numbers).parallel().sum()

Real-World Use Cases

  • Finance: Calculate total expenses or revenue
  • Statistics: Sum data points for analysis
  • Gaming: Calculate total score
  • E-commerce: Calculate cart total
›Short versionOpen if you only have a minute.
  • Start a total at 0 and add each element once.
  • An empty array sums to 0. Starting from nums[0] throws on that array.
  • An int total wraps. Integer.MAX_VALUE plus 1 becomes Integer.MIN_VALUE.
  • A long accumulator is the small change that keeps a large int array honest.

Sum an array

Accumulate every array element into a running total.

Working approach

  • Initialize the total to 0, not to the first element.
  • Use a long when the elements are ints that can sum past Integer.MAX_VALUE.
  • Do not sort or copy the array. One pass adds.

Walk the sample

  1. Values 2, 4, 6
  2. Total moves 0, 2, 6, 12
  3. The result is 12

The trap

The sample {2, 4, 6} fits in an int. A pair of large values wraps, and the method returns a negative total for positive inputs.

java
static long sum(int[] values) {
    long total = 0;
    for (int value : values) {
        total += value;
    }
    return total;
}

What is the int sum of Integer.MAX_VALUE and 1?

Integer.MIN_VALUE. The add wraps.

Accumulating in a long holds 2147483648. An empty array never enters the loop and correctly returns 0.

Time O(n), space O(1).

Easy to get wrong

  • Initializing from nums[0] without an empty check, then also looping from 0 and counting it twice.
  • Using an int total for a large array.