Infinite recursion exhausts the JVM call stack.
A StackOverflowError is thrown by the JVM when the call stack overflows due to excessive recursion. Each method call consumes stack space; with unbounded recursive calls, the stack runs out of memory. Note: this is an `Error`, not an `Exception`, meaning it represents a JVM-level problem.
This is almost always caused by a recursive method that either has no base case, has an unreachable base case, or has a base case that requires too many steps. It can also be triggered by mutual recursion (A calls B which calls A) with no termination condition.
1public class Fibonacci {2 public static int fib(int n) {3 // Missing base cases — this recurses infinitely for most inputs4 return fib(n - 1) + fib(n - 2);5 }6 7 public static void main(String[] args) {8 System.out.println(fib(10));9 }10}1public class Fibonacci {2 // Fix 1: Add proper base cases3 public static int fib(int n) {4 if (n <= 0) return 0; // Base case 15 if (n == 1) return 1; // Base case 26 return fib(n - 1) + fib(n - 2);7 }8 9 // Fix 2: Use dynamic programming (iterative) for large N10 public static long fibIterative(int n) {11 if (n <= 0) return 0;12 if (n == 1) return 1;13 long a = 0, b = 1;14 for (int i = 2; i <= n; i++) {15 long next = a + b;16 a = b;17 b = next;18 }19 return b;20 }21 22 public static void main(String[] args) {23 System.out.println(fib(10)); // 5524 System.out.println(fibIterative(50)); // 1258626902525 }26}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
The `fib` method calls itself with `n-1` and `n-2` but has no base case to stop at `n == 0` or `n == 1`. The recursion decrements `n` below 0 indefinitely, and the call stack fills up until the JVM throws `StackOverflowError`.