StackOverflowError in Java — What It Means and How to Fix It

What Java's StackOverflowError means and how to fix it.

Published November 2, 2026

StackOverflowError is thrown when the call stack is exhausted, almost always by infinite or very deep recursion.

What it means and why it happens

Each method call uses stack space; without a base case the stack fills up.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
java.lang.StackOverflowError

Practical examples

Code that triggers it

int f(int n) { return f(n + 1); }

The fix

int f(int n) {
    if (n >= 100) return n;
    return f(n + 1);
}

Iterate or increase stack

for (int i = 0; i < n; i++) { /* loop */ }
// java -Xss4m App   (last resort)

Common mistakes

  • Missing base case.
  • Cyclic toString/equals/hashCode calling each other.
  • Raising -Xss instead of fixing recursion.

Key takeaways

  • StackOverflowError: StackOverflowError is thrown when the call stack is exhausted, almost always by infinite or very deep recursion.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Can I catch it?

Technically, but you should fix the recursion.

How do I find which line caused StackOverflowError?

The error message and stack trace show the file and line; start there and work backwards.

More Java articles