In this tutorial, you will learn about Java recursive function, its advantages and disadvantages.
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called recursive function. This technique provides a way to break complicated problems down into simple problems which are easier to solve.
Recursion may be a bit difficult to understand when encountering it for the first time, the best way to figure out how it works is to experiment with it.
In the above example, we have called the recurse() method from inside the main method. (normal method call). And, inside the recurse() method, we are again calling the same recurse method. This is a recursive call.
In order to stop the recursive call, we need to provide some conditions inside the method. Otherwise, the method will be called infinitely.
In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems.
In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached.int fact(int n)
{
if (n < = 1)
return 1;
else
return n*fact(n-1);
}
Let us take the example how recursion works by taking a simple function.
// A Java program to demonstrate working of
// recursion
class Codemistic {
static void printFun(int test)
{
if (test < 1)
public static void main(String[] args)
{
int test = 3;
printFun(test);
}
}
// This code is contributed by
// Smitha Dinesh Semwal
output
3 2 1 1 2 3
When a recursive call is made, new storage locations for variables are allocated on the stack. As, each recursive call returns, the old variables and parameters are removed from the stack. Hence, recursion generally uses more memory and is generally slow.
On the other hand, a recursive solution is much simpler and takes less time to write, debug and maintain.