Find Sum of Array in Java
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).
Algorithm
Initialize sum
Start with sum = 0.
Traverse array
Visit each element once in a loop.
Accumulate
Add each value into running sum.
📜 Pseudocode
function arraySum(arr):
sum = 0
for each value in arr:
sum = sum + value
return sumSum of a fixed array
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);
}
}Sum of user input array
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
🔄 Input / output examples
| Array | Sum |
|---|---|
{1,2,3,4,5} | 15 |
{} | 0 |
Edge cases and pitfalls
Summing is straightforward, but these cases are commonly asked in interviews.
Empty array
No elements means total stays 0.
Large totals
Use long to reduce overflow risk when numbers are large.
Validate parsing
Reject malformed tokens in user input before summing.
⏱️ Time and space complexity
| Approach | Time | Extra space |
|---|---|---|
| Single traversal sum | O(n) | O(1) |
Summary
- Pattern: initialize
sum = 0, then add each value once. - Type: use
longfor safer totals. - Complexity:
O(n)time andO(1)extra space.
Summing an array is the simplest form of the accumulator pattern: start with 0 and keep adding each element.
9 people found this page helpful
