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.
When designing a recursive method keep in mind that you need:
Base Case. This will define when your recursion will stop and output the result. The base case in the factorial example is:
if (n <= 1) {
return 1;
}
Recursive Call. In this statement you re-call the method with a changed parameter. The recursive call in the factorial example above is:
else {
return n * factorial(n - 1);
}
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
...
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 Deep recursion is problematic in Java