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:


Recursion:
* Recursion

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
50 Recursion
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap