Module 4 · Methods — topic 3 of 3
Recursion
Methods that call themselves: base cases and recursive cases, the call stack, classic examples, memoisation, and when to prefer iteration.
Learning objectives
- Identify the base case and recursive case of a problem
- Trace recursive calls on the call stack
- Improve exponential recursion with memoisation
Definition
Recursion is a technique in which a method solves a problem by calling itself on smaller instances of the same problem until it reaches a base case that can be answered directly.
Introduction
Some problems are naturally defined in terms of themselves. The factorial of n is n times the factorial of n − 1; the files in a folder are the files directly inside it plus the files in each sub-folder. Recursion lets your code follow that definition directly.
Why it matters
Trees, graphs, file systems, sorting algorithms such as merge sort and quicksort, and backtracking puzzles are all expressed most clearly with recursion.
Recursion questions are a staple of programming interviews.
Detailed explanation
Every recursive method needs a base case that returns without recursing, and a recursive case that moves towards the base case. Without the base case — or if the arguments don't get smaller — the recursion never ends.
Each call gets its own stack frame holding its parameters and local variables. When the base case returns, the frames unwind one by one, each finishing its own computation.
The stack has a limited size (typically a few thousand to tens of thousands of frames). Recursing too deeply throws StackOverflowError. Java does not optimise tail calls, so a deeply recursive loop should be rewritten iteratively.
Naive recursion can repeat work: computing Fibonacci with fib(n - 1) + fib(n - 2) makes an exponential number of calls. Memoisation stores each answer the first time it is computed (in an array or map), turning exponential time into linear time.
Divide and conquer splits a problem into halves, solves each recursively and combines the results — binary search, merge sort and fast exponentiation all work this way.
Any recursion can be converted into a loop (sometimes with an explicit stack). Prefer recursion when it makes the code clearly simpler, and iteration when depth could be large.
Syntax
- Make sure every recursive call moves closer to a base case.
- Check invalid input (such as negative n) before recursing.
- Use long or BigInteger when results grow quickly.
Code examples
Factorial, sum of digits and power
120 2432902008176640000 35 1024 1594323
Watching the call stack
enter 3
enter 2
enter 1
enter 0
return 0
return 1
return 3
return 6More examples
Memoised Fibonacci, binary search and permutations
fib(25) = 75025 using 242785 calls fib(90) = 2880067194370816120 index of 42: 4, of 5: -1 [abc, acb, bac, bca, cab, cba]
Step-by-step explanation
fibNaiverecomputes the same values again and again: 242,785 calls just for fib(25).fibMemostores each result inmemo; every value from 2 to 90 is computed once, so fib(90) is instant.binarySearchhalves the range on every call and stops whenlo > hi(not found) or the middle element matches.lo + (hi - lo) / 2computes the midpoint without overflowing for very large indexes.permutefixes each remaining character in turn and recurses on the others; the base case adds a finished permutation to the list.
Expected output
Running “Memoised Fibonacci, binary search and permutations” prints exactly:
Practical applications
- Walking directory trees and parsing nested data such as JSON or XML
- Sorting with merge sort and quicksort
- Backtracking solvers for Sudoku, mazes and N-Queens
- Evaluating expression trees in compilers and calculators
Best practices
- Write the base case first.
- Use memoisation whenever the same arguments recur.
- Convert to iteration when recursion depth can reach thousands.
Common mistakes
No base case or no progress
Avoid
Prefer
Without a base case the method calls itself until the stack overflows.
Exponential recursion on large inputs
Avoid
Prefer
Overlapping subproblems must be cached; otherwise the running time grows exponentially.
Important notes
- The default thread stack can usually hold around 10,000 simple frames, but the exact limit depends on the JVM and the frame size.
- fib(93) overflows long; use java.math.BigInteger for larger values.
Key takeaways
- Recursion needs a base case and progress towards it.
- Each call has its own stack frame; too many cause StackOverflowError.
- Memoisation removes repeated work in overlapping recursions.
Try it yourself
- 1Write a recursive method that reverses a string.
- 2Solve the Tower of Hanoi for n disks and print each move; how many moves are needed for n = 10?
Finished reading? Mark it complete to update your dashboard.
Suggested practice
9 questions test this exact topic. Answers and explanations are revealed after you submit.
- BeginnerWhat is printed?
- BeginnerWhat happens if a recursive method has no reachable base case?
- BeginnerWhat is printed?