Quick Answer
Caused by excessive recursion or circular dependencies.
Understanding the Issue
The JVM throws this error when the call stack exceeds its limit, typically from infinite recursion or very deep method nesting.
The Problem
This code demonstrates the issue:
Java
Error
// Problem: Infinite recursion
public class Factorial {
public int calculate(int n) {
return n * calculate(n-1); // Missing base case
}
}
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Add base case
public int calculate(int n) {
if (n <= 1) return 1;
return n * calculate(n-1);
}
// Solution 2: Iterative approach
public int calculate(int n) {
int result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
Key Takeaways
Always define base cases in recursion or convert to iteration.