The StackOverflowError is thrown when the JVM's call stack runs out of space. This typically happens due to infinite recursion "” a method that calls itself without a proper base case, causing the stack to grow until it overflows.
// ❌ Problem "” no base case
int factorial(int n) {
return n * factorial(n - 1); // Infinite recursion!
}
// ✅ Solution "” add base case
int factorial(int n) {
if (n <= 1) return 1; // Base case stops recursion
return n * factorial(n - 1);
}
// ✅ Better "” use iteration for large n
long factorialIterative(int n) {
long result = 1;
for (int i = 2; i <= n; i++) result *= i;
return result;
}
int sum(int n) {
return n + sum(n - 1); // ❌ No base case "” infinite recursion!
}
int sum(int n) {
if (n <= 0) return 0; // ✅ Base case
return n + sum(n - 1);
}
class Node {
Node next;
@Override
public String toString() {
return "Node{next=" + next + "}"; // ❌ Calls next.toString() → infinite if circular!
}
}
class Node {
int value;
Node next;
@Override
public String toString() {
// ✅ Don't recurse into next "” just show value
return "Node{value=" + value + ", hasNext=" + (next != null) + "}";
}
}
// Recursive Fibonacci (can overflow for large n)
int fibRecursive(int n) {
if (n <= 1) return n;
return fibRecursive(n - 1) + fibRecursive(n - 2);
}
// ✅ Iterative Fibonacci (no stack overflow)
long fibIterative(int n) {
if (n <= 1) return n;
long a = 0, b = 1;
for (int i = 2; i <= n; i++) {
long temp = a + b;
a = b;
b = temp;
}
return b;
}
// ✅ Or use explicit stack for tree traversal
void traverseIterative(TreeNode root) {
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
System.out.println(node.value);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
}
It's caused by infinite recursion "” a method calling itself without a proper base case, or a base case that's never reached. Each method call adds a frame to the call stack, which eventually runs out of space.
Add or fix the base case in your recursive method. Verify the recursion actually moves toward the base case. Consider converting to an iterative solution for large inputs.
Yes, use the JVM flag -Xss: java -Xss4m MyProgram. But this is a workaround "” fixing the recursion logic is the proper solution.
Tail recursion is when the recursive call is the last operation in the method. Some languages optimize this to avoid stack growth, but Java does not perform tail call optimization.
Use a loop with an explicit Stack or Deque to simulate the call stack. Push items to process, pop and process them, push their children. This is the standard approach for tree/graph traversal.
Explore 500+ free tutorials across 20+ languages and frameworks.