Stack Overflow Error: When Recursion Goes Too Deep
What you'll learn: You'll discover what happens when recursion spins out of control and crashes your program.
What Is a Stack Overflow Error?
When a recursive method calls itself repeatedly, Java creates a new stack frame for each call. The call stack has limited memory. If you make too many recursive calls without reaching a base case, you'll run out of stack space and Java throws a StackOverflowError, crashing your program.
Think of it like stacking plates: you can only stack so high before the tower collapses. Each recursive call adds another plate. Without a base case to stop the stacking, gravity (limited memory) wins.
Common Causes
Missing Base Case:
public static int badFactorial(int n) {
return n * badFactorial(n - 1); // No base case!
// Crashes after thousands of calls
}
Base Case Never Reached:
public static int countdown(int n) {
if (n == 0) {
return 0; // Base case
}
return countdown(n + 1); // Wrong direction! Goes up instead of down
}
Incorrect Base Condition:
public static int broken(int n) {
if (n == 1) {
return 1;
}
return n * broken(n - 2); // Skips over 1 when n is even
}
The Error Message
When this happens, you'll see:
Exception in thread "main" java.lang.StackOverflowError
Prevention Checklist
- Always define a clear base case
- Ensure every recursive call moves toward the base case
- Test with small inputs first
- Consider using iteration for very deep operations
Key Takeaway: A StackOverflowError occurs when recursion exhausts the call stack—almost always because your base case is missing, wrong, or unreachable. Always verify your recursion eventually stops!