Java Recursion: Understanding, Examples, and Trade‑Offs
Java Recursion
This guide explains Java’s recursive methods, walks through a classic factorial example, and evaluates the pros and cons of using recursion.
In Java, a method that calls itself is called a recursive method, and the overall technique is known as recursion. A simple real‑world illustration is two mirrors facing each other: every reflection is another mirror image, repeating until the light is absorbed.
How Recursion Works

In the illustration above, the recurse() method is invoked from main()—a normal call. Inside recurse(), the same method calls itself again, creating a recursive call. To prevent infinite looping, each recursive call must include a termination condition, typically implemented with an if…else statement.
Example: Factorial of a Number Using Recursion
class Factorial {
static int factorial(int n) {
if (n != 0) // termination condition
return n * factorial(n - 1); // recursive call
else
return 1;
}
public static void main(String[] args) {
int number = 4, result;
result = factorial(number);
System.out.println(number + " factorial = " + result);
}
}
Output:
4 factorial = 24
The factorial() method is called from main() with the argument number. Inside factorial(), the line
return n * factorial(n-1);
causes the method to invoke itself with a decremented value. Starting with n = 4, the calls progress: 4 → 3 → 2 → 1 → 0. When n reaches 0, the if condition fails, returning 1. The accumulated product then propagates back up the call stack to main().
How the Factorial Program Executes
The image below illustrates the call stack evolution during execution.

Advantages and Disadvantages of Recursion
- Pros: Simplifies code for problems that naturally fit recursive patterns (e.g., tree traversals, combinatorial generation). Often results in shorter, more readable implementations.
- Cons: Each recursive call consumes stack space; deep recursion can lead to stack overflow. Recursive solutions are typically less memory‑efficient and may run slower than iterative counterparts.
Overall, recursion offers elegant solutions at the cost of higher memory usage and potential performance overhead. For many use‑cases, especially those with limited depth, the trade‑off is worthwhile.
Recommended Reading: What are the advantages and disadvantages of recursion?
Java
- Mastering C++ Recursion: Concepts, Examples, and Best Practices
- Mastering Python Recursion: How Functions Call Themselves
- Java Methods: How to Define, Call, and Use Them Effectively
- Mastering Method Overriding in Java
- Mastering Java Polymorphism: Concepts, Examples, and Best Practices
- Java Annotation Types: A Comprehensive Guide to Predefined, Custom, and Meta Annotations
- Mastering Java's Iterator Interface: Practical Guide with Code Example
- Mastering Java Methods: Create, Invoke, and Abstraction
- Java Method Overriding: Customizing Superclass Behavior
- Mastering Java 8: A Comprehensive Guide to Method References