Learn how methods solve complex problems by calling themselves
Recursion is a programming technique where a method calls itself to solve a smaller instance of the same problem. Think of it like a set of Russian nesting dolls—each doll contains a smaller version of itself inside until you reach the smallest, solid doll.
The condition that terminates the recursion. Without a base case, your program will execute infinitely until it triggers a StackOverflowError.
The part where the method calls itself with modified parameters that move closer to the base case.
Calculating the factorial of a number ($n! = n \times (n-1) \times \dots \times 1$) is the classic example of recursion.
class RecursionDemo {
// Recursive (non-static) function to calculate factorial
public int factorial(int n) {
// 1. Base Case
if (n <= 1) {
return 1;
}
// 2. Recursive Case
return n * factorial(n - 1);
}
}
public class Main {
public static void main(String[] args) {
RecursionDemo demo = new RecursionDemo();
int number = 4;
int result = demo.factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
}