Recursion in Java — Java Technical Interview Questions & Answers
Recursion in Java
Recursion in Java
- Recursion is a method calling itself. Write the base case first: if (n <= 1) return 1; then the step: return n * fact(n - 1);. No base case → StackOverflowError.
- Trace fact(5) on paper: 5*4*3*2*1. Recursion uses the call stack. Deep recursion can blow memory. Some problems are clearer as loops.
- Use recursion when the problem is the same shape smaller: factorial, tree walk, simple Fibonacci demo.
- Let's take this on the board with one tiny Main class — no extra files. Recursion in Java — output: 120. fact(5) → 5*fact(4) → … → 5*4*3*2*1. Stop when n <= 1. Start from main, go line by line, and stop at each print. That output is the proof for Recursion.
Technical Interview Tip: Say base case first, then the recursive step. Trace fact(5).
Code Examples for Recursion in Java
Example
public class Main {
static int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println(fact(5)); // 120
}
}Recursion in Java — output: 120. fact(5) → 5*fact(4) → … → 5*4*3*2*1. Stop when n <= 1.
How to Explain Recursion in Java to an Interviewer
What is recursion?
Method calls itself
What if there is no base case?
StackOverflowError