Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Recursion

    The Idea

    A recursive method is a method that calls itself on a smaller version of the problem.

    Chapter 1 of 94 min read

    Start With the Problem#

    StudyBuddy lets students organise notes in folders — and folders inside folders, as deep as they like:

    Output
    Semester1/            (1 note)
      Biology/            (2 notes)
        Lab/              (3 notes)
      Chemistry/          (1 note)
        Organic/          (0 notes)
          Exams/          (1 note)

    "How many notes are in Semester1, including everything inside it?" Try writing that with loops. One loop handles the top folder. A nested loop handles its subfolders. Another nested loop for their subfolders… but how many loops do you write, when a student can nest folders 50 levels deep? You can't know in advance.

    Now notice something: "count the notes in Semester1" is the same question as "count Semester1's own notes, plus the notes in Biology, plus the notes in Chemistry" — and "count the notes in Biology" is the same kind of question again, just smaller. A problem made of smaller copies of itself is solved most naturally by a method that calls itself. That's recursion.

    The Plain Picture#

    Russian nesting dolls. To find the tiny solid doll in the middle: open the doll in front of you. If it's the solid one — you're done. If not, there's a slightly smaller doll inside — and you do exactly the same thing to it.

    Or: you're in a long cinema queue in the dark and want to know your position. You ask the person in front, "what's your position?" They don't know either, so they ask the person in front of them… until the person at the very front says "I'm number 1!" Then each person adds 1 and passes the answer back.

    The Real Names#

    • A recursive method is a method that calls itself on a smaller version of the problem.

    • Every correct recursion has three parts:

      1. Base case — the smallest version, answered directly without recursion (the solid doll; the person at the front).

      2. Recursive case — express the answer using the answer to a smaller version (open the doll; ask the person in front).

      3. Progress — every recursive call must move closer to the base case, or it never ends.

    Java
    static int factorial(int n) {
        // n! = n × (n−1) × ... × 1       e.g. 4! = 24
        if (n <= 1) return 1; // 1. base case
        return n * factorial(n - 1); // 2. recursive case — 3. progress: n−1 is smaller
    }

    "4! is 4 times 3!" — the definition of factorial is itself recursive, so the code reads almost like the maths.

    Check yourself

    3 questions
    1

    Name the three parts every correct recursion needs.

    Show answer

    A base case, a recursive case, and progress toward the base case.

    2

    In the cinema-queue story, what is the base case and what is the recursive step?

    Show answer

    Base case: the person at the front knows they're number 1. Recursive step: ask the person in front and add 1 to their answer.

    3

    What happens if a recursion never reaches its base case?

    Show answer

    It recurses until the stack runs out — a StackOverflowError.