On this page (10 sections)
Java for Beginners · Module 5: Data and Methods
🎯 A Method That Calls Itself
Imagine standing in a queue and wanting to know your position. You ask the person ahead: “What is your position?” They ask the next person, and so on, until the first person answers “1”. Each person then adds 1 to the answer they receive. That is recursion: solving a problem by asking a smaller version of the same problem.
1️⃣ Factorial: The First Example
The factorial of n is n × (n – 1) × … × 1. Notice that n! = n × (n - 1)!, so the problem contains a smaller copy of itself.
| Part | Job | In factorial |
| Base case | stops the recursion; answer known directly | if (n <= 1) return 1; |
| Recursive case | calls itself with a smaller problem | return n * fact(n - 1); |
Figure 2: The two parts of every recursive method.
public class Factorial {
static int fact(int n) {
if (n <= 1) {
return 1;
}
return n * fact(n - 1);
}
public static void main(String[] args) {
System.out.println("0! = " + fact(0));
System.out.println("5! = " + fact(5));
System.out.println("10! = " + fact(10));
System.out.println("13! (overflows int) = " + fact(13));
}
}
0! = 1
5! = 120
10! = 3628800
13! (overflows int) = 1932053504
- The base case
n <= 1returns 1 without calling again. It is what ends the chain. - The recursive case calls
fact(n - 1), a smaller problem, and multiplies the answer byn. - 13! is 6,227,020,800, which does not fit in an
int, so it overflows to a wrong number (Lesson 8). Uselongfor larger factorials.
2️⃣ Watching the Calls Happen
fact(4)4 * fact(3)
fact(3)3 * fact(2)
fact(2)2 * fact(1)
fact(1)base case: returns 1
Figure 1: The call stack of fact(4): calls pile up, then answers return one by one.
public class Trace {
static int fact(int n, int depth) {
String pad = " ".repeat(depth);
System.out.println(pad + "fact(" + n + ") called");
if (n <= 1) {
System.out.println(pad + "base case, returns 1");
return 1;
}
int result = n * fact(n - 1, depth + 1);
System.out.println(pad + "fact(" + n + ") returns " + result);
return result;
}
public static void main(String[] args) {
fact(4, 0);
}
}
fact(4) called
fact(3) called
fact(2) called
fact(1) called
base case, returns 1
fact(2) returns 2
fact(3) returns 6
fact(4) returns 24
- The indentation shows the depth. Each call waits, unfinished, while the next call runs.
- Only when
fact(1)returns do the waiting calls finish, in reverse order: 2, then 6, then 24. - The waiting calls are held on the call stack, a part of memory with one frame per active call (Lesson 4).
3️⃣ More Recursive Classics
public class Classics {
static int sumTo(int n) {
return n == 0 ? 0 : n + sumTo(n - 1);
}
static int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}
static int fib(int n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static String reverse(String s) {
if (s.isEmpty()) return s;
return reverse(s.substring(1)) + s.charAt(0);
}
static int digitSum(int n) {
return n == 0 ? 0 : n % 10 + digitSum(n / 10);
}
public static void main(String[] args) {
System.out.println("sumTo(5) = " + sumTo(5));
System.out.println("power(2, 10) = " + power(2, 10));
System.out.print("fib 0..9 = ");
for (int i = 0; i < 10; i++) System.out.print(fib(i) + " ");
System.out.println();
System.out.println("gcd(48, 18) = " + gcd(48, 18));
System.out.println("reverse(Java) = " + reverse("Java"));
System.out.println("digitSum(4728)= " + digitSum(4728));
}
}
sumTo(5) = 15
power(2, 10) = 1024
fib 0..9 = 0 1 1 2 3 5 8 13 21 34
gcd(48, 18) = 6
reverse(Java) = avaJ
digitSum(4728)= 21
sumTo(n)is n plus the sum up to n – 1.power(b, e)is b times b to the power e – 1. Anything to the power 0 is 1 (the base case).fib(n)is the sum of the two previous Fibonacci numbers. It has two recursive calls and two base cases (0 and 1).gcdis Euclid’s method: the gcd of a and b is the gcd of b and the remainder a % b, until the remainder is 0.reversereverses everything after the first character, then puts the first character at the end.digitSumadds the last digit to the digit sum of the rest (compare with the loop version in Lesson 18).
4️⃣ When Recursion Is Slow: Memoization
fib(4)fib(3)fib(2)fib(3) ➜ fib(2) + fib(1)fib(2) ➜ fib(1) + fib(0)fib(2) is worked out more than once. For fib(30) this repeats work over 2.6 million times. Remembering earlier answers (memoization) fixes it.Figure 4: Plain recursive Fibonacci repeats the same work.
public class FibSpeed {
static long calls = 0;
static long slow(int n) {
calls++;
if (n <= 1) return n;
return slow(n - 1) + slow(n - 2);
}
static long[] memo = new long[60];
static long fast(int n) {
if (n <= 1) return n;
if (memo[n] != 0) return memo[n];
memo[n] = fast(n - 1) + fast(n - 2);
return memo[n];
}
public static void main(String[] args) {
System.out.println("slow fib(30) = " + slow(30) + " using " + calls + " calls");
System.out.println("fast fib(30) = " + fast(30));
System.out.println("fast fib(50) = " + fast(50));
}
}
slow fib(30) = 832040 using 2692537 calls
fast fib(30) = 832040
fast fib(50) = 12586269025
- The plain version made over 2.6 million calls just to find
fib(30), because it recomputes the same values again and again. - The fast version stores each answer in the array
memothe first time and reuses it. This idea is called memoization and is the first step towards dynamic programming. - With memoization,
fib(50)is instant. The plain version would take a very long time.
5️⃣ Recursion or Loop?
| Recursion | Loop | |
| Idea | method calls itself on a smaller problem | repeat a block with a counter |
| Memory | one stack frame per call | constant |
| Risk | StackOverflowError if too deep | infinite loop |
| Best for | trees, divide-and-conquer, naturally recursive definitions | simple counting and repeating |
Figure 3: Recursion versus loops.
Anything written with recursion can be written with a loop, and the other way round. Choose recursion when the problem is naturally defined in terms of itself (trees, folders inside folders, divide-and-conquer). Choose a loop for plain counting.
6️⃣ The Error Beginners Meet: StackOverflowError
public class Inf {
static int broken(int n) {
return n + broken(n + 1);
}
public static void main(String[] args) {
System.out.println(broken(1));
}
}
Exception in thread “main” java.lang.StackOverflowError
at Inf.broken(Inf.java:3)
at Inf.broken(Inf.java:3)
at Inf.broken(Inf.java:3)
… (thousands of identical lines)
- This method has no base case, so it calls itself forever. Each call uses stack memory, which eventually runs out, and Java stops the program with
StackOverflowError. - When you see many repeated lines of the same method, look for a missing or unreachable base case.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
| No base case | StackOverflowError | Always write the stopping condition first |
| Recursive call that does not get smaller | Never reaches the base case | Move towards it: n - 1, n / 10, a shorter String |
| Forgetting to use the returned value | Answer is lost | return n * fact(n - 1); |
| Plain recursive Fibonacci for large n | Exponentially slow | Memoize, or use a loop |
Using int for big factorials | Overflow | Use long or BigInteger |
| Checking the base case after the recursive call | Call happens too late | Check the base case first |
❓ Frequently Asked Questions
Q1. How deep can recursion go in Java?
Usually a few thousand to tens of thousands of calls, depending on the stack size and the method. Very deep problems should use loops.
Q2. Is recursion faster than a loop?
Usually not. Each call has a small cost. Recursion is chosen for clarity.
Q3. What is tail recursion?
A recursive call that is the very last action. Some languages optimise it into a loop, but Java does not.
Q4. Can a method call another method that calls it back?
Yes. That is mutual recursion, and it also needs base cases.
✅ Key Takeaways
- A recursive method calls itself on a smaller version of the problem.
- It needs a base case (stop) and a recursive case (progress).
- Calls pile up on the call stack, then return in reverse order.
- No base case means
StackOverflowError. - Repeated work, as in plain Fibonacci, can be removed with memoization.
🎓 Practice questions: (1) Write a recursive method to print the numbers from n down to 1. (2) Write a recursive method that counts the digits of a number. (3) Check if a String is a palindrome recursively. (4) Tracepower(2, 4)by hand, writing each call. (5) Explain whyfib(5)callsfib(2)more than once.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java