Recursion in Java is a programming technique where a method calls itself to solve a problem by breaking it into smaller subproblems. Each recursive call works on a reduced version of the original problem until a base condition is met.
A recursive method in Java consists of two essential parts:
// Recursive method syntax in Java
returnType methodName(parameters) {
// base condition
if(condition) {
return value;
}
// recursive call
return methodName(modifiedParameters);
}
// Java program to calculate factorial using recursion
class Factorial {
static int factorial(int n) {
// base condition to stop recursion
if(n == 0) {
return 1;
}
// recursive call
return n * factorial(n - 1);
}
public static void main(String[] args) {
int result = factorial(5);
System.out.println(result);
}
}
120
The method keeps calling itself by reducing the value of n until it reaches 0. Once the base case is reached, values are returned step-by-step to compute the final result.
Visualize how the Stack Frame builds up and unwinds during recursion.