Recursion

suggest change

Introduction

Recursion occurs when a method calls itself. Such a method is called recursive. A recursive method may be more concise than an equivalent non-recursive approach. However, for deep recursion, sometimes an iterative solution can consume less of a thread’s finite stack space.

This topic includes examples of recursion in Java.

Remarks

Designing a Recursive Method

When designing a recursive method keep in mind that you need:

if (n <= 1) {
    return 1;
}
else {
    return n * factorial(n - 1);
}

Output

In this example you compute the n-th factorial number. The first factorials are:

0! = 1

1! = 1

2! = 1 x 2 = 2

3! = 1 x 2 x 3 = 6

4! = 1 x 2 x 3 x 4 = 24


Java and Tail-call elimination

Current Java compilers (up to and including Java 9) do not perform tail-call elimination. This can impact the performance of recursive algorithms, and if the recursion is deep enough, it can lead to StackOverflowError crashes; see http://stackoverflow.com/documentation/java/914/recursion/15048/deep-recursion-is-problematic-in-java#t=201611080249331156811

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents