Recursion in Java is a programming technique where a method calls itself to solve a problem. It’s commonly used when a problem can be broken down into smaller, similar sub-problems. Let’s take a look at a simple example:
javaCopy codepublic class RecursionExample {
// A recursive method to calculate the factorial of a number
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
int number = 5;
int result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}
In this example, the factorial()
method calculates the factorial of a number n
recursively. It checks for the base case where n
is either 0 or 1 and returns 1. Otherwise, it recursively calls itself with n - 1
and multiplies the result by n
. This process continues until the base case is reached, and then the results are propagated back up the call stack.
Recursion can provide an elegant solution for certain problems but requires careful handling of base cases to avoid infinite recursion.