Recursion in Java
A recursive method is one that calls itself, breaking a problem down into a smaller version of the same problem until it reaches a base case simple enough to answer directly without recursing further. Every recursive method needs exactly that: a base case that stops the recursion, and a recursive case that calls the method again with an input that's genuinely closer to that base case — without both pieces, a recursive method either never recurses at all or never stops.
Each recursive call gets its own separate space on the call stack to track its own parameters and local variables, which is why extremely deep recursion can exhaust that stack and throw a StackOverflowError — a real, practical limit that iterative loops don't share in the same way.
The base case
The simplest version of the problem, answered directly with no further recursive call.
The recursive case
Calls the method again with an input that's genuinely smaller or closer to the base case than the current one.
Every call gets its own stack frame
Each recursive call tracks its own copy of parameters and local variables, entirely separate from every other call.
Unwinding
Once the base case is reached, each waiting call resumes and completes in reverse order, from the deepest call back to the original one.
The risk of unbounded recursion
A recursive case that never actually approaches the base case recurses forever, in practice throwing a StackOverflowError once the call stack fills up.
public class RecursionDemo { 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(4)); }}The stack-space cost is easy to overlook, since it doesn't show up as extra work in the code itself — it's a direct consequence of how many calls are waiting on the stack at the deepest point of recursion.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.