A recursive method is a method that calls itself to solve a smaller instance of the same problem. Recursion is often used for problems that can be divided into sub-problems, such as factorial calculation or traversing trees.
Example of Recursion (Factorial Calculation):
public class RecursiveMethodExample {
// Recursive method to calculate factorial
public int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
RecursiveMethodExample example = new RecursiveMethodExample();
int result = example.factorial(5); // Calculate factorial of 5
System.out.println("Factorial of 5: " + result);
}
}
Factorial of 5: 120