πŸ”§ Error Fixes
Β· 1 min read

Java: StackOverflowError β€” How to Fix It


java.lang.StackOverflowError means the call stack exceeded its size limit β€” usually from infinite recursion.

What causes this error

  1. Infinite recursion β€” a method calls itself without a proper base case
  2. Circular references β€” A calls B, B calls A
  3. 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