Tracing
Recursion
Learn to trace recursive method calls, understand call stack behavior, and predict the output of recursive Java programs.
What Is Recursion?
A recursive method is a method that calls itself. Each call works on a smaller version of the original problem until it reaches a base case: a condition where it stops calling itself and returns a value directly.
The Call Stack
Every time a method is called, Java creates a stack frame and pushes it onto the call stack. The frame stores the method's local variables and its return address. When the method returns, its frame is popped off the stack.
Anatomy of a Recursive Method
Two Phases: Winding and Unwinding
Every recursion has two phases. During winding, the method pushes new calls onto the stack. During unwinding, each call returns its result to the caller.
Recursion vs Iteration
| Recursion | Iteration | |
|---|---|---|
| Mechanism | Method calls itself | Loop repeats a block |
| Memory | Uses call stack frames | Uses loop variables |
| Termination | Base case | Loop condition false |
| Risk | StackOverflowError | Infinite loop |
| Best for | Tree/graph traversal, divide-and-conquer | Simple counting, linear scans |
How to Trace Recursion
Example 1: Recursive Sum
Trace sum(4):
Example 2: Print Order Matters
Example 3: String Recursion
Trace reverse("cat"):
Example 4: Fibonacci (Two Recursive Calls)
Trace fib(4): each call spawns two sub-calls, creating a tree.
Call Stack Snapshot
Here is the call stack at the deepest point of factorial(4), just before the base case returns:
Stack Unwinding in Action
Once the base case returns, frames pop one at a time, each substituting the returned value:
Common Mistakes
Recursion Cheat Sheet
| Concept | What to Look For | Key Rule |
|---|---|---|
| Base case | if/return with no recursive call | Must be reachable |
| Recursive case | Method calls itself | Argument must shrink |
| Winding phase | Calls stacking up | Print before call: top-down |
| Unwinding phase | Returns flowing back | Print after call: bottom-up |
| Stack depth | Count of active frames | Too deep = StackOverflow |
| Tree recursion | Two+ recursive calls (fib) | Exponential call count |
Question 1 of 5
public static int mystery(int n) {
if (n == 0) return 2;
return 2 * mystery(n - 1);
}
What is the value of mystery(3)?
Question 2 of 5
public static void printStuff(int n) {
if (n <= 0) return;
printStuff(n - 1);
System.out.print(n + " ");
}
What does printStuff(4) output?
Question 3 of 5
public static int recur(int n) {
if (n <= 1) return n;
return recur(n - 1) + recur(n - 2);
}
How many total calls to recur() are made when evaluating recur(5)? (Include the initial call.)
Question 4 of 5
A recursive method has no base case. What happens when it is called?
Question 5 of 5
public static String build(int n) {
if (n == 0) return "";
return build(n - 1) + n;
}
What does build(4) return?