# Java recursive functions explained // Using recursion to sum an array of numbers

Recursion is one of the methods in computer science that can be used to solve a problem. Java is a very powerful object-oriented language which allows you to use recursion. If you search for recursion in Wikipedia you will find this definition:

Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own definition.

This means that a function will call itself indefinitely.
However, it is often done in a way that the function will call itself until it reaches a certain condition and stops.
This condition is also called the **base case**.

There are many pages where you can find great explanations to recursion theory. Most of them use the example of the Towers of Hanoi:

In this post, I'm going to show you a simple example of recursion in Java. I'm going to use it to sum an array of numbers. The example illustrates how easy it is to use recursion and how useful it can be.

```
import java.math.BigDecimal;
public class Recursion {
public static void main(String[] args) {
// We create the array of numbers we want to sum,
// It can be any subclass of java.lang.Number
Number[] test = {100, 0.05d, 1391L, 88d, 99d, 0.0037, 0.05d, 0.05d, 88d, 99d, -528.15, 0.13f};
// We call our recursive function
System.out.println(sum(test));
}
// This is the initial function
// Calls the recursive function with the initial, default values
static Number sum(Number[] numbers) {
if (numbers.length < 1) {
return 0;
}
return sum(BigDecimal.valueOf(0), numbers, numbers.length - 1);
}
// The recursive function
static Number sum(BigDecimal initialValue, Number[] numbers, int location) {
// If we've reached the end of the array we return the final result (base case)
if (location < 0) {
return initialValue;
}
// Otherwise, recursively call the function with the next number in the array
else {
int nextLocation = location - 1;
Number current = numbers[location];
// Convert the current number to BigDecimal
// We can now add it to the initialValue with precision (or perform any arithmetic operation)
return sum(initialValue.add(new BigDecimal(current.toString())), numbers, nextLocation);
}
}
}
```

## Comments in "Java recursive functions explained // Using recursion to sum an array of numbers"

Functional programming languages like Haskell or Erlang do provide tail call optimization and in these languages a recursive call is just as expensive as an iteration.

You can read more about this issue at IBM: Diagnosing java code...