java.lang.StackOverflowError means the call stack exceeded its size limit β usually from infinite recursion.
What causes this error
- Infinite recursion β a method calls itself without a proper base case
- Circular references β A calls B, B calls A
- Very deep recursion β legitimate recursion thatβs too deep for the stack
Fix 1: Add or fix the base case
// β No base case β infinite recursion
int factorial(int n) {
return n * factorial(n - 1);
}
// β
Base case stops recursion
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Fix 2: Convert recursion to iteration
// β
Iterative β no stack overflow risk
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
Fix 3: Increase stack size (last resort)
java -Xss4m MyApp # Increase stack to 4MB (default ~512KB)
How to find the recursion
The stack trace shows the same method name repeated hundreds of times. Look at that method and find where it calls itself.
Related: Java cheat sheet Β· Java: OutOfMemoryError fix Β· Stack Overflow Error fix