Writing
Recursive Methods
Learn to design methods that call themselves, define correct base cases, and build elegant solutions to complex problems in Java.
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.
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.
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.
Anatomy of a Recursive Method
Every well-written recursive method has exactly two parts: one that stops and one that continues.
The Two Golden Rules
Correct recursion requires satisfying both of these rules. Violating either one leads to infinite recursion and a StackOverflowError.
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
if statement at the top of the method to catch it.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\).
// Base case: single digit
if (n < 10)
return n;
// Recursive case: last digit + rest
return n % 10 + sumDigits(n / 10);
}
Tracing sumDigits(123)
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}\).
// 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".
// 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.
// 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
if check that stops recursion. Java throws a StackOverflowError when the call stack fills up.f(n) calls f(n) again. The parameter must move toward the base case.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?
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?
if (n == 0) return 0;
return 1 + count(n);
}
count(n) passes the same value of n every time. It should be count(n - 1) so the parameter decreases toward the base case of 0.