SteelReed

Search

Search posts, questions…

Collections & DSAQuestion 17 / 25

Junior

What is a recursion base case, and why can recursive code cause StackOverflowError in production?

Short answer

The base case is recursion's stopping condition; every call must move closer to it. With no base case, or recursion that goes too deep, the JVM throws StackOverflowError.

YesNocloser to base casetoo deepCall f(n)Base case?Return resultCall f(n - 1)one more frameStackOverflowError

3 points to say:

  1. Each call takes one frame on the stack.
  2. Java does not optimize tail calls.
  3. For large data, switch to a loop.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.