Recursion in Java is a technique where a method calls itself to solve a problem. It helps break a complex problem into smaller parts.
Recursion means calling the same method repeatedly until a stopping condition is reached.
The base case is the condition that stops recursion.
The recursive case is where the method calls itself with smaller input.
returnType methodName(parameters) {
if (condition) {
return value;
}
return methodName(smallerInput);
}
public class RecursionExample {
static int factorial(int n) {
if (n == 1) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
| Step | Process |
|---|---|
| factorial(5) | 5 × factorial(4) |
| factorial(4) | 4 × factorial(3) |
| factorial(3) | 3 × factorial(2) |
| factorial(2) | 2 × factorial(1) |
| factorial(1) | Returns 1 (Base Case) |
Recursion is a powerful concept in Java where a method calls itself until a base condition is met.
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.