R
Rishtaara
Java Fundamentals
Lesson 12 of 36Article14 min

Recursion

A recursive method solves a problem by calling itself on a smaller part. You need a base case to stop.

Recursion — method calls itself

A recursive method solves a problem by calling itself on a smaller part. You need a base case to stop.

Without base case you get StackOverflowError — infinite calls.

Real-life example: Russian nesting dolls — open one doll, find smaller doll inside, repeat until the tiniest solid doll (base case).

Factorial with recursion
static int factorial(int n) {
    if (n <= 1) return 1;       // base case
    return n * factorial(n - 1);
}

public static void main(String[] args) {
    System.out.println(factorial(5)); // 120
}

When to use recursion

Good for trees, divide-and-conquer, and problems that mirror smaller versions (Fibonacci, directory walk).

For simple loops, a for or while is often clearer and faster.

Real-life example: Finding a file in nested folders — check this folder, if not found, recurse into subfolders.

Sum array with recursion
static int sumArray(int[] arr, int index) {
    if (index >= arr.length) return 0;
    return arr[index] + sumArray(arr, index + 1);
}