Find Sum of Array in Java

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Arrays

What you’ll learn

  • Accumulator pattern with sum += value.
  • Fixed-array and user-input variants in Java.
  • Handling empty arrays and negative values safely.
  • Why complexity is linear in number of elements.

Overview

Array sum means adding every element exactly once. For {1,2,3,4,5}, result is 15. This is the core accumulator pattern used in many interview problems.

Two Java programs

Fixed array sum and user-input array sum.

Live preview

Paste values like 10, -2, 7 and compute instantly.

Safe sum type

Use long when totals might exceed int.

Live preview

Enter integers separated by commas or spaces (for example: 1 2 3 or 1,2,3).

Negatives are allowed. Empty input is treated as no values.

Live result
Press “Compute sum”.

Algorithm

Initialize sum

Start with sum = 0.

Traverse array

Visit each element once in a loop.

Accumulate

Add each value into running sum.

📜 Pseudocode

Pseudocode
function arraySum(arr):
  sum = 0
  for each value in arr:
    sum = sum + value
  return sum
1

Sum of a fixed array

java
public class Main {
    static long sumArray(int[] arr) {
        long sum = 0;
        for (int i = 0; i < arr.length; i++) {
            sum += arr[i];
        }
        return sum;
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        long sum = sumArray(array);
        System.out.println("Sum of the array elements: " + sum);
    }
}
2

Sum of user input array

java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();
        if (n < 0) {
            System.out.println("Invalid n.");
            return;
        }

        long sum = 0;
        for (int i = 0; i < n; i++) {
            System.out.print("Enter element " + (i + 1) + ": ");
            long x = sc.nextLong();
            sum += x;
        }
        System.out.println("Sum of the array elements: " + sum);
    }
}

Optimization notes

One pass is already optimal for exact sum; use long to reduce overflow risk.

❓ FAQ

Initialize sum = 0 and loop through array: sum += arr[i].
0 is the identity for addition, so it does not change the total.
Yes. The same loop works for positive, zero, and negative values.
Use long if values or count can be large to reduce overflow risk.
O(n), because each element is visited once.

🔄 Input / output examples

ArraySum
{1,2,3,4,5}15
{}0

Edge cases and pitfalls

Summing is straightforward, but these cases are commonly asked in interviews.

n = 0

Empty array

No elements means total stays 0.

Overflow

Large totals

Use long to reduce overflow risk when numbers are large.

Input errors

Validate parsing

Reject malformed tokens in user input before summing.

⏱️ Time and space complexity

ApproachTimeExtra space
Single traversal sumO(n)O(1)

Summary

  • Pattern: initialize sum = 0, then add each value once.
  • Type: use long for safer totals.
  • Complexity: O(n) time and O(1) extra space.
Did you know?

Summing an array is the simplest form of the accumulator pattern: start with 0 and keep adding each element.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful