01 / 20

Writing
Recursive Methods

Learn to design methods that call themselves, define correct base cases, and build elegant solutions to complex problems in Java.

AP Computer Science A

What Is Recursion?

Recursion is a programming technique where a method calls itself to solve a smaller version of the same problem. Each call brings you closer to a simple case you can solve directly.

Base Case
The condition that stops the recursion: a problem small enough to solve directly.
Recursive Case
The method calls itself with a smaller or simpler input, moving toward the base case.

Why Use Recursion?

Some problems are naturally recursive: their structure breaks into identical sub-problems. Recursion lets you express solutions that mirror the problem's own definition.

Elegant Code
Recursive solutions are often shorter and more readable than iterative loops for tree/graph traversals.
Mirrors Math
Mathematical definitions like \(n!\) and Fibonacci are naturally recursive, making code match the formula.
Divide & Conquer
Algorithms like merge sort and binary search split problems in half: recursion handles each half.

Visualizing the Call Stack

Each recursive call adds a frame to the call stack. When the base case is reached, frames unwind in reverse order, returning results back up the chain.

factorial(4) factorial(3) factorial(2) factorial(1) factorial(0) = 1 BASE CASE returns 1 returns 1 returns 2 returns 6 CALL PHASE ↓ RETURN PHASE ↑

Anatomy of a Recursive Method

Every well-written recursive method has exactly two parts: one that stops and one that continues.

public static int factorial ( int n ) { if (n == 0 ) return 1 ; ← BASE CASE return n * factorial (n - 1 ); ← RECURSIVE CASE } Parameter n shrinks toward 0 with each call

The Two Golden Rules

Correct recursion requires satisfying both of these rules. Violating either one leads to infinite recursion and a StackOverflowError.

1
Base case exists and is reachable. There must be at least one condition where the method returns a result without calling itself.
2
Each recursive call must make progress toward the base case. The argument must change (usually decrease) so the method eventually reaches the base case.

Recursion vs. Iteration

Both techniques repeat work, but they differ in how they track state and when each is the better fit.

Recursion Iteration
State storage Call stack frames Loop variables
Termination Base case Loop condition false
Risk StackOverflowError Infinite loop
Best for Trees, divide & conquer Counters, simple repeats
Readability Mirrors math definitions Familiar to beginners

How to Write a Recursive Method

1
Define the method signature. Decide the return type and what parameter(s) will shrink toward the base case.
2
Identify the base case. What is the simplest input? What should the method return for that input?
3
Write the base case first. Use an if statement at the top of the method to catch it.
4
Write the recursive case. Express the current answer in terms of a smaller call. Make sure the argument changes.
5
Trace by hand. Walk through 2-3 small inputs to verify correctness and termination.

Example 1: Sum of Digits

Write a method that returns the sum of the digits of a non-negative integer. For example, sumDigits(123) returns \(1 + 2 + 3 = 6\).

public static int sumDigits(int n) {
  // Base case: single digit
  if (n < 10)
    return n;

  // Recursive case: last digit + rest
  return n % 10 + sumDigits(n / 10);
}

Tracing sumDigits(123)

sumDigits(123) 123 % 10 = 3 sumDigits(12) 12 % 10 = 2 sumDigits(1) → returns 1 1 1 + 2 = 3 3 + 3 = 6 ✓

Example 2: Computing \(b^n\)

Write a method that computes \(b^n\) for non-negative integer \(n\). By definition: \(b^0 = 1\) and \(b^n = b \times b^{n-1}\).

public static int power(int b, int n) {
  // Base case: anything to the 0th power is 1
  if (n == 0)
    return 1;

  // Recursive case: b * b^(n-1)
  return b * power(b, n - 1);
}

Example 3: Reverse a String

Write a method that reverses a String. For instance, reverse("hello") returns "olleh".

public static String reverse(String s) {
  // Base case: empty or single character
  if (s.length() <= 1)
    return s;

  // Recursive case: last char + reverse of the rest
  return s.charAt(s.length() - 1)
    + reverse(s.substring(0, s.length() - 1));
}

Example 4: isPalindrome

Check if a string reads the same forwards and backwards. This shows a recursive method with a boolean return type.

public static boolean isPalindrome(String s) {
  // Base case: 0 or 1 chars is a palindrome
  if (s.length() <= 1)
    return true;

  // Check first and last chars, recurse on middle
  return s.charAt(0) == s.charAt(s.length() - 1)
    && isPalindrome(s.substring(1, s.length() - 1));
}

Common Mistakes

✕ Missing Base Case
Forgetting the if check that stops recursion. Java throws a StackOverflowError when the call stack fills up.
✕ No Progress
Passing the same argument unchanged: f(n) calls f(n) again. The parameter must move toward the base case.
✕ Wrong Base Case Value
The base case exists but returns the wrong result. For example, returning 0 instead of 1 for factorial(0).

Recursion Pattern Summary

Method Base Case Recursive Call Progress
\(\text{factorial}(n)\) \(n = 0 \to 1\) \(n \times f(n-1)\) \(n-1\)
\(\text{sumDigits}(n)\) \(n < 10 \to n\) \(n\pmod{10} + f(n/10)\) \(n/10\)
\(\text{power}(b, n)\) \(n = 0 \to 1\) \(b \times f(b, n-1)\) \(n-1\)
\(\text{reverse}(s)\) \(\text{len} \le 1 \to s\) \(\text{last} + f(\text{rest})\) \(\text{len} - 1\)
\(\text{isPalindrome}(s)\) \(\text{len} \le 1 \to \text{true}\) \(\text{match} \land f(\text{mid})\) \(\text{len} - 2\)

Question 1 of 5

What is the base case in the following recursive method?

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

Question 2 of 5

What does sumDigits(305) return?

Question 3 of 5

Which of the following methods will cause a StackOverflowError?

Question 4 of 5

What does power(3, 4) return?

Question 5 of 5

A student writes the following method. What is wrong?

public static int count(int n) {
  if (n == 0) return 0;
  return 1 + count(n);
}