⏱️ 9 min read • Beginner Level • Lesson 36
Recursion in Java is a programming technique where a method calls itself to solve a problem. A recursive method keeps calling itself until a stopping condition is reached.
Before learning recursion, you should understand Java Methods, Java Method Parameters, and Java Method Overloading.
Recursion is a technique where a method solves a problem by calling itself again with a smaller or simpler input. This continues until the problem reaches a condition where no more recursive call is needed.
returnType methodName(parameters) {
if (baseCondition) {
return value;
}
return methodName(smallerInput);
}
Recursion is commonly used when a problem can be divided into smaller versions of the same problem.
Every recursive call is stored in memory as a separate method call. Java uses the call stack to keep track of these method calls. When the base condition is reached, the methods start returning back one by one.
A recursive method usually has two important parts: base case and recursive case.
| Part | Meaning |
|---|---|
| Base Case | The stopping condition that prevents infinite recursion. |
| Recursive Case | The part where the method calls itself with a smaller or simpler input. |
StackOverflowError.
In this example, the method prints numbers from 1 to 5 using recursion.
public class SimpleRecursionExample {
static void printNumbers(int number) {
if (number > 5) {
return;
}
System.out.println(number);
printNumbers(number + 1);
}
public static void main(String[] args) {
printNumbers(1);
}
}
Output:
1 2 3 4 5
printNumbers(1) starts the recursive process.number > 5 is the base case.printNumbers(number + 1) calls the same method with the next number.
Factorial of a number means multiplying that number by all positive numbers below it.
For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.
public class FactorialRecursion {
static int factorial(int number) {
if (number <= 1) {
return 1;
}
return number * factorial(number - 1);
}
public static void main(String[] args) {
System.out.println("Factorial: " + factorial(5));
}
}
Output:
Factorial: 120
factorial(5) is called from the main() method.number == 1. When number becomes 1, the method returns 1.number * factorial(number - 1).5 * factorial(4), then 4 * factorial(3), and so on.5 * 4 * 3 * 2 * 1, which gives 120.
We can use recursion to calculate the sum of natural numbers up to a given number.
For example, sum up to 5 is 5 + 4 + 3 + 2 + 1 = 15.
public class SumNaturalNumbers {
static int sum(int number) {
if (number == 0) {
return 0;
}
return number + sum(number - 1);
}
public static void main(String[] args) {
System.out.println("Sum: " + sum(5));
}
}
Output:
Sum: 15
sum(5) starts the recursive calculation.number == 0, which returns 0.number + sum(number - 1).5 + 4 + 3 + 2 + 1 + 0.15.In the Fibonacci series, each number is the sum of the previous two numbers. The series starts with 0 and 1.
public class FibonacciRecursion {
static int fibonacci(int number) {
if (number == 0) {
return 0;
}
if (number == 1) {
return 1;
}
return fibonacci(number - 1) + fibonacci(number - 2);
}
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
Output:
0 1 1 2 3 5 8
fibonacci() returns the Fibonacci number at a given position.number == 0 and number == 1.fibonacci(number - 1) + fibonacci(number - 2).fibonacci(i) for values from 0 to 6.Recursion can also be used to print numbers in reverse order.
public class ReverseNumbersRecursion {
static void printReverse(int number) {
if (number == 0) {
return;
}
System.out.println(number);
printReverse(number - 1);
}
public static void main(String[] args) {
printReverse(5);
}
}
Output:
5 4 3 2 1
printReverse(5) starts printing from 5.number == 0, the method stops.number - 1.
If a recursive method does not stop, it keeps adding method calls to the call stack.
Eventually, the stack becomes full and Java throws a StackOverflowError.
public class InfiniteRecursion {
static void callAgain() {
System.out.println("Calling...");
callAgain(); // no base case
}
public static void main(String[] args) {
callAgain();
}
}
callAgain() prints a message.StackOverflowError.| Iteration | Recursion |
|---|---|
Uses loops like for, while, or do-while. |
Uses a method calling itself. |
| Usually uses less memory. | Uses call stack memory for each method call. |
| Good for simple repeated tasks. | Good for problems that can be divided into smaller similar problems. |
| No risk of stack overflow from method calls. | Can cause stack overflow if base case is missing. |
| Easier to optimize for performance. | Can be easier to understand for recursive problems. |
The following example demonstrates multiple recursive methods in one program.
public class JavaRecursionCompleteExample {
static int factorial(int number) {
if (number == 1) {
return 1;
}
return number * factorial(number - 1);
}
static int sum(int number) {
if (number == 0) {
return 0;
}
return number + sum(number - 1);
}
static void countdown(int number) {
if (number == 0) {
System.out.println("Done");
return;
}
System.out.println(number);
countdown(number - 1);
}
public static void main(String[] args) {
System.out.println("Factorial of 5: " + factorial(5));
System.out.println("Sum up to 5: " + sum(5));
countdown(3);
}
}
Output:
Factorial of 5: 120 Sum up to 5: 15 3 2 1 Done
factorial() calculates the factorial of a number using recursion.sum() calculates the sum of natural numbers up to the given number.countdown() prints numbers in decreasing order and stops at 0.main() method calls all three recursive methods and prints the results.| Concept | Description |
|---|---|
| Recursion | A method calling itself |
| Base Case | Stopping condition |
| Recursive Case | Method calls itself |
| Memory Used | Call Stack |
| Risk | StackOverflowError |
| Alternative | Loops (Iteration) |
StackOverflowError.🧠 Test your understanding with a quick quiz
Topic: Recursion | Language: Java
static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}public class Test {
static void print(int n) {
if (n > 3) {
return;
}
System.out.print(n + " " );
print(n + 1);
}
public static void main(String[] args) {
print(1);
}
}static int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}public class Test {
static int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
public static void main(String[] args) {
System.out.println(sum(5));
}
}static void printReverse(int n) {
if (n == 0) {
return;
}
System.out.print(n + " " );
printReverse(n - 1);
}🎉 Great job! Continue learning Java step by step.