English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn about Java recursive functions and their advantages and disadvantages.
In Java, a method that calls itselfMethodIt is called a recursive method. And, this process is called recursion.
A physical world example is placing two parallel mirrors facing each other. Any object between them will be recursively reflected.
In the above example, we called the recurse() method from within the main method. (Normal method call). And, within the recurse() method, we call the same recurse method again. This is a recursive call.
To stop the recursive calls, we need to provide some conditions within the method. Otherwise, the method will be called infinitely.
Therefore, we useif ... else statement(or similar method) terminate the recursive call within the method.
class Factorial { static int factorial(int n) { if (n != 0) // termination condition return n * factorial(n-1); //recursive call else return 1; } public static void main(String[] args) { int number = 4, result; result = factorial(number); System.out.println(number + "factorial of " + result()); } }
output:
4 factorial of 24
In the above example, we have a method named factorial(). It is called from the main() method. It uses the passed number variable as an argument.
Here, please note the following statement:
return n * factorial(n-1);
factorial() method is calling itself. Initially, the value of n inside factorial() is4. During the next recursive call, the3to the factorial() method. This process continues until n equals 0.
When n equals 0, the if statement returns false, so return1. Finally, the accumulated result is passed to the main() method.
The following diagram will help you better understand how to use recursion to execute the factorial program.
When making a recursive call, a new variable storage location is allocated on the stack. As each recursive call returns, the old variables and parameters are removed from the stack. Therefore, recursion usually uses more memory and is usually slower.
On the other hand, the recursive solution is much simpler and takes less time to write, debug, and maintain.