Skip Top Navigation Bar

An Introduction to Recursion

Recursion happens when a method calls itself. This is a repetitive process that continues and progresses until a base case is reached.

There are two critical parts to a recursive method.

Without a proper progression towards the base case, the code could result in infinite recursion. This is where the program continues to call the recursive method without a stopping point.

Consider the following example of a recursive method and a call to that method.

When evaluating a recursive method call, it can be helpful to trace through the method to determine the result and visualize the way the recursive method is functioning. At first, we are unable to evaluate what sum(3) will return, since it is dependent on the value of sum(2), which is dependent on the value of sum(1). Once we have reached the base case, sum(1), the return value of this call can be used to evaluate the return value of sum(2) and so on until we have computed the return value of sum(3) which is 6.

To further illustrate:

sum(3) = 3 + sum(2)
sum(2) = 2 + sum(1)
sum(1) = 1

Now, we can work our way from the bottom back to the top to complete the trace.

sum(2) = 2 + sum(1) = 2 + 1 = 3
sum(3) = 3 + sum(2) = 3 + 3 = 6

Your Turn

Let's try it in the Java Playground.

Complete List of Recursion Tutorials

Resources