Video in progress

What is recursion, and what happens if there is no base case?

Recursion is a method calling itself with a smaller problem. The base case is the condition that stops the calls. If it's missing or never reached, the stack fills up and you get a StackOverflowError.

📖 Answer

Every recursive call adds a new frame to the thread's stack: parameters, local variables, the return address. When the base case is reached, the frames unwind in reverse order.

static int sumDigits(int n) {
    if (n < 10) return n;              // base case
    return n % 10 + sumDigits(n / 10); // the problem is getting smaller
}

For recursion to be correct, you need two things: there is a base case, and every call moves closer to it. For example with sumDigits(-5), n < 10 is true right away, so there's no problem. But if you mistakenly write n + 1 instead of n - 1, the depth grows without bound.

Java doesn't do tail call optimization. With the default stack size, the depth is usually a few thousand to tens of thousands, depending on the frame size. So walking a 100,000-element list with recursion is a bad idea; write a plain loop there.