Array Sum Using Recursion in Java
Problem
Summing an array recursively means adding the current element to whatever the recursive call over the rest of the array returns, one index at a time, until there's nothing left to add.
Given an array of integers, find the sum of its elements using recursion.
Java Program
public class ArraySumRecursion {
static int sum(int[] arr, int index) {
if (index == arr.length) return 0; // nothing left to add
return arr[index] + sum(arr, index + 1);
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
System.out.println("Sum: " + sum(arr, 0));
}
}Output
Core Logic
Adding the element at the current index to the sum of everything after it reduces the whole array's total to a chain of single-element additions.
- 1
sum(arr, index)tracks how far into the array the current call has reached. - 2The base case
if (index == arr.length) return 0;fires once every index has been visited, contributing nothing further. - 3Every other call returns
arr[index] + sum(arr, index + 1), adding its own element to whatever the rest of the array sums to. - 4The very first call,
sum(arr, 0), ends up holding the total once every deeper call has returned.
[2, 4, 6, 8, 10], the calls unwind as 10+0=10, 8+10=18, 6+18=24, 4+24=28, 2+28=30, so the total is 30.Key Point: The addition happens on the way back up the call stack, not on the way down — each call has to wait for the deeper call to return before it can compute its own contribution.
Why: One recursive call handles one array element, so both the call count and the stack depth grow with the array's length n.
Key Concepts
Approach 2: Java 8
import java.util.Arrays;
public class ArraySumStream {
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10};
int total = Arrays.stream(arr).sum();
System.out.println("Sum: " + total);
}
}
Output
Core Logic
Arrays.stream(arr).sum() reduces the whole array to a total directly, without a recursive call for every element.
- 1
Arrays.stream(arr)converts theint[]into anIntStream. - 2
.sum()reduces every element of the stream down to a single total. - 3No index tracking or recursive calls are needed — the stream handles the traversal internally.
[2, 4, 6, 8, 10], .sum() reduces the stream straight to 30, the same total the recursive version computes.Key Point: Unlike the recursive version, this doesn't add a stack frame per element — the stream's internal iteration keeps memory use flat regardless of the array's length.
Why: sum() visits each of the n elements once internally, without recursing or allocating anything proportional to the array's size.