Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 05 / Topic 6 of 7

Recursion

A recursive method calls itself on a smaller version of the same problem. Think of nested Pune tiffin boxes: open one, there is a smaller one inside, until the smallest box that does not open. That smallest case is the base case — it stops the calls. Every recursive method needs one, or it never stops.

Real-world example: the sum of the digits of a number.

static int sumOfDigits(int n) {
    if (n < 10) {            // base case: one digit
        return n;
    }
    return n % 10 + sumOfDigits(n / 10);   // last digit + digits of the rest
}

System.out.println(sumOfDigits(560001));     // 12
System.out.println(sumOfDigits(7));           // 7

Real-world example: applying a discount percentage over and over, a fixed number of rounds.

static double applyRepeatedDiscount(double price, double percentOff, int rounds) {
    if (rounds == 0) {                        // base case: no rounds left
        return price;
    }
    double afterOneRound = price - (price * percentOff / 100);
    return applyRepeatedDiscount(afterOneRound, percentOff, rounds - 1);
}

System.out.println(applyRepeatedDiscount(1000.0, 10.0, 0));   // 1000.0
System.out.println(applyRepeatedDiscount(1000.0, 10.0, 1));   // 900.0
System.out.println(applyRepeatedDiscount(1000.0, 10.0, 3));   // 729.0

What happens without a base case

Each method call waits on the call stack (one "sheet of paper" from section 5, stacked on top of the last) until its own call returns. A recursive method with no base case keeps stacking calls until Java runs out of stack space and throws a StackOverflowError:

static void blowTheStack(int depth) {
    blowTheStack(depth + 1);     // no base case: this never stops on its own
}

try {
    blowTheStack(0);
} catch (StackOverflowError error) {
    System.out.println("Caught: " + error.getClass().getSimpleName());
}
// Caught: StackOverflowError

StackOverflowError is a real, catchable Error in Java (Part 6 covers exceptions and errors properly) — but relying on it to stop a bad recursion is a bug, not a strategy. Always write the base case first.

🔍 Going deeper: deep recursion also costs real memory and time — every pending call sits on the stack until it returns. For a problem that naturally runs thousands of rounds deep, a for or while loop (Part 3) is almost always the better choice; recursion earns its keep when the "smaller problem" shape — a number's digits, a folder inside a folder — makes the code clearly simpler to read.

Full program: examples/05_recursion_basics.java.

Done here? The practice set for Part 5 — including the solutions — is on the part page.

Search the guide