Sum of Array in Java: Solution, Explanation & Practice

Calculate the sum of array elements

Problem summary

Find the sum of all elements in the array [5, 10, 15, 20, 25].

Starter code

public class Main {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        
        // Calculate and print sum
        // Print: Sum: <result>
    }
}

Expected output and test cases

  • Sum of array
    Sum: 75

Hints

  1. Initialize sum to 0
  2. Add each element to sum
  3. Use for-each or regular for loop

Validated solution

Reveal Java solution
public class Main {
    static int sum(int[] values) {
        int total = 0;
        for (int value : values) total += value;
        return total;
    }

    public static void main(String[] args) {
        int[] values = {5, 10, 15, 20, 25};
        System.out.println("Sum: " + sum(values));
    }
}

How to approach the problem

A running total is the smallest state needed. After each iteration it equals the sum of every value already visited, which makes the empty-array result naturally zero.

Approach

  1. Start with the additive identity, zero.
  2. Visit each element once.
  3. Add the current value to the running total.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • An empty array has sum zero.
  • Many large ints can overflow int; promote total to long when required.

Common mistakes

  • Initializing total to the first element and then failing on empty input.
  • Using a nested loop and counting values repeatedly.

Follow-up challenge

Return both the sum and an overflow-safe average as a small result object.

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler