# Java Recursion

Contents

## Java Recursion

Java Recursion: In this tutorial, you will find out about Java recursive function, its advantages, and its disadvantages.

In Java, a method that calls itself is known as a recursive method. What’s more, this cycle is known as recursion.

A physical world example is a place two equal mirrors confronting one another. Any object in the middle of them would be reflected recursively.

## How Recursion works?

In the above example, we have called the recurse() method from inside the main method. (normal method calls). Furthermore, inside the recurse() strategy, we are again calling the equivalent recurse technique. This is a recursive call.

So as to stop the recursive call, we have to give a few conditions inside the strategy. Something else, the strategy will be called limitlessly.

Hence, we use the if…else statement (or similar approach) to terminate the recursive call inside the method.

## Example: Factorial of a Number Using Recursion

``````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 = " + result);
}
}``````

Output

``4 factorial = 24``

In the above example, we have a method named factorial(). The factorial() is called from the main() method. with the number variable passed as an argument.

Here, notice the statement,

``return n * factorial(n-1);``

The factorial() method is calling itself. Initially, the value of n is 4 inside factorial(). During the next recursive call, 3 is passed to the factorial() method. This process continues until n is equal to 0.

When n is equal to 0, the if statement returns false hence 1 is returned. Finally, the accumulated result is passed to the main() method.

## Working of Factorial Program

The picture beneath will give you a superior thought of how the factorial program is executed using recursion.

At the point when a recursive call is made, new storage locations for variables are distributed on the stack. As each recursive call returns, the old variables and parameters are taken out from the stack. Consequently, recursion, by and large, uses more memory and is commonly slow.

Then again, a recursive arrangement is a lot easier and sets aside less effort to write, troubleshoot, and keep up.