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:
if (n <= 1) {
return 1;
}
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
…