Recursive :- Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method. It makes the code compact but complex to understand.
A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Key points to keep in mind when working with recursion in Java:
Example :-
public class RecursionExample
{
public static void main(String[] args)
{
int result = factorial(5);
System.out.println(“Factorial of 5 is: ” + result);
}
public static int factorial(int n)
{
// Base case: If n is 0 or 1, return 1.
if (n == 0 || n == 1)
{
return 1;
}
else {
// Recursive case: Call the factorial function with a smaller value.
return n * factorial(n – 1);
}
}
}
Output :- Factorial of 5 is : 120
Advantages of Recursive Programming
The advantages of recursive programs are as follows:
Disadvantages of Recursive Programming
The disadvantages of recursive programs is as follows:
Note :- Both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true.