Recursion & Varargs
What is recursion?
A recursive method solves a problem by calling itself on a smaller version of the same problem.
Every recursive method needs two parts:
- Base case – the simplest input, answered directly. This stops the recursion.
- Recursive case – breaks the problem down and calls itself.
static int factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
factorial(4) → 4 * 3 * 2 * 1 → 24
How it works: the call stack
Each call waits on the stack until the one it made returns. With no base case (or a very deep input) you get a StackOverflowError 💥.
Recursion vs loops
- Recursion shines for naturally recursive problems: trees, folders, maze solving, divide-and-conquer sorts.
- Loops are usually faster and use less memory for simple counting.
- Naive recursive Fibonacci repeats the same work many times. Fix it with a loop or by caching results (memoization).
Varargs — any number of arguments
static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(); // 0
sum(1, 2, 3); // 6
Rules:
- Inside the method,
numsis just an array. - Only one varargs parameter per method, and it must be last:
void log(String level, String... messages).
Example
public class Recursion {
static int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
static int countDigits(int n) {
if (n < 10) return 1;
return 1 + countDigits(n / 10);
}
static int max(int first, int... rest) {
int best = first;
for (int n : rest) best = Math.max(best, n);
return best;
}
public static void main(String[] args) {
System.out.println(factorial(5)); // 120
System.out.println(countDigits(2026)); // 4
System.out.println(max(4, 9, 2, 7)); // 9
}
}