Java Recursion
Recursion is when a method calls itself. It is a natural way to solve problems that can be broken into smaller versions of the same problem — counting down, walking through nested folders, or exploring a family tree.
Every recursive method needs two parts:
- A base case — a simple situation that is answered directly, without another call.
- A recursive case — the method calls itself with a smaller input that moves toward the base case.
A first example
class Main {
static void countdown(int n) {
if (n == 0) { // base case
System.out.println("Go!");
return;
}
System.out.println(n);
countdown(n - 1); // recursive case: smaller problem
}
public static void main(String[] args) {
countdown(3);
}
}3
2
1
Go!
Recursion that returns a value
The sum of the numbers 1 to n can be defined as "n plus the sum of 1 to n-1":
class Main {
static int sumTo(int n) {
if (n <= 0) {
return 0;
}
return n + sumTo(n - 1);
}
public static void main(String[] args) {
System.out.println(sumTo(5));
System.out.println(sumTo(100));
}
}15
5050
How sumTo(4) unfolds:
sumTo(4) = 4 + sumTo(3)
= 4 + (3 + sumTo(2))
= 4 + (3 + (2 + sumTo(1)))
= 4 + (3 + (2 + (1 + sumTo(0))))
= 4 + 3 + 2 + 1 + 0
= 10Each call waits on the call stack until the call below it returns. Once the base case is reached, the results are combined on the way back up.
Classic recursive problems
Factorial, powers and the greatest common divisor (Euclid's algorithm) all have elegant recursive definitions:
class Main {
static long factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
static long power(long base, int exp) {
if (exp == 0) return 1;
long half = power(base, exp / 2); // halve the problem each time
return exp % 2 == 0 ? half * half : half * half * base;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) {
System.out.println("10! = " + factorial(10));
System.out.println("3^13 = " + power(3, 13));
System.out.println("gcd(84, 36) = " + gcd(84, 36));
}
}10! = 3628800
3^13 = 1594323
gcd(84, 36) = 12
Recursion on strings and arrays
Recursion works on any data you can shrink — for example by dropping the first character of a string or by narrowing an index range:
class Main {
static String reverse(String s) {
if (s.length() <= 1) return s;
return reverse(s.substring(1)) + s.charAt(0);
}
static boolean isPalindrome(String s, int left, int right) {
if (left >= right) return true;
if (s.charAt(left) != s.charAt(right)) return false;
return isPalindrome(s, left + 1, right - 1);
}
static int max(int[] a, int i) {
if (i == a.length - 1) return a[i];
return Math.max(a[i], max(a, i + 1));
}
public static void main(String[] args) {
System.out.println(reverse("recursion"));
String w = "racecar";
System.out.println(w + " palindrome? " + isPalindrome(w, 0, w.length() - 1));
System.out.println("max = " + max(new int[] {3, 17, 8, 11}, 0));
}
}noisrucer
racecar palindrome? true
max = 17
The danger: no base case
If the base case is missing or never reached, the method calls itself until the call stack runs out of space and Java throws a StackOverflowError:
static int broken(int n) {
return n + broken(n - 1); // no base case - never stops
}Even correct recursion can overflow for very deep inputs (tens of thousands of levels). For simple counting problems a loop is usually more efficient; recursion shines on naturally nested structures such as trees.
| Recursion | Loop | |
|---|---|---|
| Code style | short, mirrors the definition | explicit steps |
| Memory | one stack frame per call | constant |
| Best for | trees, divide and conquer, backtracking | simple repetition |
Test yourself
What does every recursive method need to stop?
- A loop
- A base case
- A static field
- A return type of void
What does f(4) return for static int f(int n) { return n == 0 ? 0 : 2 + f(n - 1); }?
- 4
- 6
- 8
- 10
Which error occurs when recursion never reaches a base case?
- NullPointerException
- OutOfMemoryError
- StackOverflowError
- ArithmeticException