Skip to content

Recursion in Java

Imagine you have a magic mirror. When you look into it, you see another mirror inside it, and inside that mirror, there's yet another mirror, and so on. That's a bit like recursion in Java!

In programming, recursion is like a mirror reflecting itself over and over until it reaches a stopping point. Let's say you want to count down from 5 to 1. Instead of using a loop, you can use recursion.

Here's how it works: You tell Java to count down from a number. Java counts down one number at a time, but then it remembers that it needs to count down again, starting from the next number. It's like having a little helper inside Java that keeps reminding it what to do next.

But here's the cool part: Recursion isn't just about counting down. It's like a superpower that lets you solve big problems by breaking them into smaller, more manageable pieces.

For example, think about a Russian nesting doll. It's a doll inside a doll inside a doll... You get the idea. Recursion works similarly. You can solve a big problem by solving a smaller version of the same problem, over and over again until you reach the simplest version.

Program for recursion

java
public class FactorialCalculator {
    public static int factorial(int n) {
        // Base case: If n is 0 or 1, return 1
        if (n == 0 || n == 1) {
            return 1;
        } else {
            // Recursive case: n! = n * (n-1)!
            return n * factorial(n - 1);
        }
    }

    public static void main(String[] args) {
        int number = 5;
        int result = factorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }
}

In our example, we have a factorial() method that calculates the factorial of a given number. But here's where the magic happens—instead of using a loop, we call the factorial() method within itself, gradually reducing the problem until we reach the base case.

As we traverse deeper into the realm of recursion, each invocation of the factorial() method brings us closer to our goal, until finally, we reach the base case where n is 0 or 1. At this point, the recursion unwinds, and the factorial values are calculated and multiplied on the way back up the call stack.

But recursion isn't just about factorial calculations; it's a powerful tool for solving a wide range of problems, from traversing tree structures to searching through arrays and beyond.

java
public class RecursionExample {
    public static void countdown(int n) {
        if (n == 0) {
            System.out.println("Blastoff!");
        } else {
            System.out.println(n);
            countdown(n - 1); // Recursive call
        }
    }

    public static void main(String[] args) {
        countdown(5);
    }
}

In our example, we have a method called countdown() that takes an integer n. If n is equal to 0, we print "Blastoff!" and stop. Otherwise, we print the current value of n and then make a recursive call to countdown(n - 1).

When we run the main() method with an initial value of 5, here's what happens:

  1. We call countdown(5).
  2. countdown(5) prints 5 and then calls countdown(4).
  3. countdown(4) prints 4 and then calls countdown(3).
  4. This process continues until countdown(0) is called, printing "Blastoff!" and stopping.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.