Beginner 20 min read

Recursion: A First Look

By the end of this lesson, you'll be able to:

  • Explain what a recursive method is
  • Identify the base case that stops a recursive method
  • Trace through a simple recursive call step by step

Prerequisites: "Method Overloading"

A method that calls itself

public Integer factorial(Integer n) {
    if (n <= 1) {
        return 1; // base case
    }
    return n * factorial(n - 1); // recursive case
}

System.debug(factorial(4)); // 24

factorial(4) calls factorial(3), which calls factorial(2), which calls factorial(1) — which hits the base case and returns 1 without calling itself again. Each call then multiplies its own n by the result coming back from the level below it.

Why the base case is non-negotiable

Without if (n <= 1) { return 1; }, factorial would call itself forever — factorial(4)factorial(3)factorial(2)factorial(1)factorial(0)factorial(-1) → ... Apex would eventually hit a stack depth limit and throw an error. Every recursive method needs a condition that stops the self-calls, exactly like a loop needs a condition that eventually becomes false.

A real-world analogy: Russian nesting dolls

Opening a set of nesting dolls means repeating the same action — open, look inside, open the next one — until you reach the smallest doll that doesn't open at all. That smallest doll is the base case; every doll before it is the recursive case, doing the same simple action and handing the "next problem" to the doll inside it.

Trade-offs and when NOT to use this

Recursion often reads more elegantly than an equivalent loop for naturally nested problems, but every recursive call adds to Apex's call stack, and deep recursion can hit governor limits faster than an equivalent loop would. For simple counting or accumulation like this factorial example, a for loop (Module 7) is usually just as clear and safer at scale — recursion earns its keep on genuinely nested structures, which later modules will revisit.

Exercise

Write a recursive method Integer sumUpTo(Integer n) that returns the sum of all integers from 1 to n (e.g., sumUpTo(4) returns 10). Include a base case for n <= 1.

Show hint

return n + sumUpTo(n - 1); with a base case returning 1 when n <= 1.

APEX

Recursion: A First Look Quiz

1. What is a base case in recursion?

2. Recursion is always safer than a loop for avoiding governor limits.

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A recursive method calls itself to solve a smaller version of the same problem — powerful for naturally nested data, but only safe with a clear stopping point.