Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 26: Recursion Basics in Java

Java for Beginners · Module 5: Data and Methods


🎯 A Method That Calls Itself

Imagine standing in a queue and wanting to know your position. You ask the person ahead: “What is your position?” They ask the next person, and so on, until the first person answers “1”. Each person then adds 1 to the answer they receive. That is recursion: solving a problem by asking a smaller version of the same problem.

📌 Recursion means a method calls itself. Every recursive method needs a base case that stops the calls and a recursive case that moves towards the base case.

1️⃣ Factorial: The First Example

The factorial of n is n × (n – 1) × … × 1. Notice that n! = n × (n - 1)!, so the problem contains a smaller copy of itself.

PartJobIn factorial
Base casestops the recursion; answer known directlyif (n <= 1) return 1;
Recursive casecalls itself with a smaller problemreturn n * fact(n - 1);
Every recursive method needs both. Without a base case, or without getting closer to it, the calls never stop.

Figure 2: The two parts of every recursive method.

public class Factorial {
    static int fact(int n) {
        if (n <= 1) {
            return 1;
        }
        return n * fact(n - 1);
    }

    public static void main(String[] args) {
        System.out.println("0! = " + fact(0));
        System.out.println("5! = " + fact(5));
        System.out.println("10! = " + fact(10));
        System.out.println("13! (overflows int) = " + fact(13));
    }
}
🖥️ Output:
0! = 1
5! = 120
10! = 3628800
13! (overflows int) = 1932053504
  • The base case n <= 1 returns 1 without calling again. It is what ends the chain.
  • The recursive case calls fact(n - 1), a smaller problem, and multiplies the answer by n.
  • 13! is 6,227,020,800, which does not fit in an int, so it overflows to a wrong number (Lesson 8). Use long for larger factorials.

2️⃣ Watching the Calls Happen

fact(4)
4 * fact(3)
fact(3)
3 * fact(2)
fact(2)
2 * fact(1)
fact(1)
base case: returns 1
Going down: each call waits for the next. Coming back: 1 → 2 × 1 = 2 → 3 × 2 = 6 → 4 × 6 = 24.

Figure 1: The call stack of fact(4): calls pile up, then answers return one by one.

public class Trace {
    static int fact(int n, int depth) {
        String pad = "  ".repeat(depth);
        System.out.println(pad + "fact(" + n + ") called");
        if (n <= 1) {
            System.out.println(pad + "base case, returns 1");
            return 1;
        }
        int result = n * fact(n - 1, depth + 1);
        System.out.println(pad + "fact(" + n + ") returns " + result);
        return result;
    }

    public static void main(String[] args) {
        fact(4, 0);
    }
}
🖥️ Output:
fact(4) called
fact(3) called
fact(2) called
fact(1) called
base case, returns 1
fact(2) returns 2
fact(3) returns 6
fact(4) returns 24
  • The indentation shows the depth. Each call waits, unfinished, while the next call runs.
  • Only when fact(1) returns do the waiting calls finish, in reverse order: 2, then 6, then 24.
  • The waiting calls are held on the call stack, a part of memory with one frame per active call (Lesson 4).

3️⃣ More Recursive Classics

public class Classics {
    static int sumTo(int n) {
        return n == 0 ? 0 : n + sumTo(n - 1);
    }

    static int power(int base, int exp) {
        if (exp == 0) return 1;
        return base * power(base, exp - 1);
    }

    static int fib(int n) {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2);
    }

    static int gcd(int a, int b) {
        return b == 0 ? a : gcd(b, a % b);
    }

    static String reverse(String s) {
        if (s.isEmpty()) return s;
        return reverse(s.substring(1)) + s.charAt(0);
    }

    static int digitSum(int n) {
        return n == 0 ? 0 : n % 10 + digitSum(n / 10);
    }

    public static void main(String[] args) {
        System.out.println("sumTo(5)      = " + sumTo(5));
        System.out.println("power(2, 10)  = " + power(2, 10));
        System.out.print("fib 0..9      = ");
        for (int i = 0; i < 10; i++) System.out.print(fib(i) + " ");
        System.out.println();
        System.out.println("gcd(48, 18)   = " + gcd(48, 18));
        System.out.println("reverse(Java) = " + reverse("Java"));
        System.out.println("digitSum(4728)= " + digitSum(4728));
    }
}
🖥️ Output:
sumTo(5) = 15
power(2, 10) = 1024
fib 0..9 = 0 1 1 2 3 5 8 13 21 34
gcd(48, 18) = 6
reverse(Java) = avaJ
digitSum(4728)= 21
  • sumTo(n) is n plus the sum up to n – 1.
  • power(b, e) is b times b to the power e – 1. Anything to the power 0 is 1 (the base case).
  • fib(n) is the sum of the two previous Fibonacci numbers. It has two recursive calls and two base cases (0 and 1).
  • gcd is Euclid’s method: the gcd of a and b is the gcd of b and the remainder a % b, until the remainder is 0.
  • reverse reverses everything after the first character, then puts the first character at the end.
  • digitSum adds the last digit to the digit sum of the rest (compare with the loop version in Lesson 18).

4️⃣ When Recursion Is Slow: Memoization

fib(4)
➜
fib(3)
fib(2)
fib(3) ➜ fib(2) + fib(1)
fib(2) ➜ fib(1) + fib(0)
fib(2) is worked out more than once. For fib(30) this repeats work over 2.6 million times. Remembering earlier answers (memoization) fixes it.

Figure 4: Plain recursive Fibonacci repeats the same work.

public class FibSpeed {
    static long calls = 0;

    static long slow(int n) {
        calls++;
        if (n <= 1) return n;
        return slow(n - 1) + slow(n - 2);
    }

    static long[] memo = new long[60];

    static long fast(int n) {
        if (n <= 1) return n;
        if (memo[n] != 0) return memo[n];
        memo[n] = fast(n - 1) + fast(n - 2);
        return memo[n];
    }

    public static void main(String[] args) {
        System.out.println("slow fib(30) = " + slow(30) + " using " + calls + " calls");
        System.out.println("fast fib(30) = " + fast(30));
        System.out.println("fast fib(50) = " + fast(50));
    }
}
🖥️ Output:
slow fib(30) = 832040 using 2692537 calls
fast fib(30) = 832040
fast fib(50) = 12586269025
  • The plain version made over 2.6 million calls just to find fib(30), because it recomputes the same values again and again.
  • The fast version stores each answer in the array memo the first time and reuses it. This idea is called memoization and is the first step towards dynamic programming.
  • With memoization, fib(50) is instant. The plain version would take a very long time.

5️⃣ Recursion or Loop?

RecursionLoop
Ideamethod calls itself on a smaller problemrepeat a block with a counter
Memoryone stack frame per callconstant
RiskStackOverflowError if too deepinfinite loop
Best fortrees, divide-and-conquer, naturally recursive definitionssimple counting and repeating

Figure 3: Recursion versus loops.

Anything written with recursion can be written with a loop, and the other way round. Choose recursion when the problem is naturally defined in terms of itself (trees, folders inside folders, divide-and-conquer). Choose a loop for plain counting.

6️⃣ The Error Beginners Meet: StackOverflowError

public class Inf {
    static int broken(int n) {
        return n + broken(n + 1);
    }

    public static void main(String[] args) {
        System.out.println(broken(1));
    }
}
🖥️ Runtime error (trimmed):
Exception in thread “main” java.lang.StackOverflowError
at Inf.broken(Inf.java:3)
at Inf.broken(Inf.java:3)
at Inf.broken(Inf.java:3)
… (thousands of identical lines)
  • This method has no base case, so it calls itself forever. Each call uses stack memory, which eventually runs out, and Java stops the program with StackOverflowError.
  • When you see many repeated lines of the same method, look for a missing or unreachable base case.

⚠️ Common Mistakes

MistakeProblemFix
No base caseStackOverflowErrorAlways write the stopping condition first
Recursive call that does not get smallerNever reaches the base caseMove towards it: n - 1, n / 10, a shorter String
Forgetting to use the returned valueAnswer is lostreturn n * fact(n - 1);
Plain recursive Fibonacci for large nExponentially slowMemoize, or use a loop
Using int for big factorialsOverflowUse long or BigInteger
Checking the base case after the recursive callCall happens too lateCheck the base case first

❓ Frequently Asked Questions

Q1. How deep can recursion go in Java?
Usually a few thousand to tens of thousands of calls, depending on the stack size and the method. Very deep problems should use loops.

Q2. Is recursion faster than a loop?
Usually not. Each call has a small cost. Recursion is chosen for clarity.

Q3. What is tail recursion?
A recursive call that is the very last action. Some languages optimise it into a loop, but Java does not.

Q4. Can a method call another method that calls it back?
Yes. That is mutual recursion, and it also needs base cases.

✅ Key Takeaways

  • A recursive method calls itself on a smaller version of the problem.
  • It needs a base case (stop) and a recursive case (progress).
  • Calls pile up on the call stack, then return in reverse order.
  • No base case means StackOverflowError.
  • Repeated work, as in plain Fibonacci, can be removed with memoization.
🎓 Practice questions: (1) Write a recursive method to print the numbers from n down to 1. (2) Write a recursive method that counts the digits of a number. (3) Check if a String is a palindrome recursively. (4) Trace power(2, 4) by hand, writing each call. (5) Explain why fib(5) calls fib(2) more than once.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision