AI Hints
Home›Java Tutorial›Recursion, Varargs, Practice: Temperature Converter
Java · Lesson 61 of 120

Recursion

A method that calls itself.

⏱ 2 min read▶ Video at 1:16:02🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A method can call itself. That's called recursion. It's a neat way to solve a problem, by solving a smaller version of the same problem.

  • Calls itself
  • Called recursion
  • Smaller and smaller

Two parts

Every recursive method needs two parts. A base case, where it stops, and returns without calling itself. And a recursive case, where it calls itself, with a smaller problem. Without a base case, it never stops.

keyvalue
Base casestop here
Recursive casecall yourself, smaller
Each callgets closer to the base
No base casecrash

Countdown and factorial

Countdown prints n, then calls itself with n minus one. When n reaches zero, the base case prints lift off, and returns. Factorial of five is five times four times three times two times one. That's five times the factorial of four. So factorial calls itself, until n is one. Run it. A countdown, then a hundred and twenty. And twenty factorial is huge, so we used long.

Main.javajava
public class Main {
    static void countdown(int n) {
        if (n == 0) {
            System.out.println("Lift off!");
            return;
        }
        System.out.print(n + " ");
        countdown(n - 1);
    }
    static long factorial(int n) {
        if (n <= 1) return 1;
        return n * factorial(n - 1);
    }
    public static void main(String[] args) {
        countdown(5);
        System.out.println("5! = " + factorial(5));
        System.out.println("20! = " + factorial(20));
    }
}
Output
5 4 3 2 1 Lift off!
5! = 120
20! = 2432902008176640000

No base case

This method calls itself forever. Each call uses a little memory, on what's called the stack. Run it. Stack overflow error. The stack ran out of space.

Main.javajava
public class Main {
    static int forever(int n) {
        return forever(n + 1);
    }

    public static void main(String[] args) {
        forever(1);
    }
}
Output
Exception in thread "main" java.lang.StackOverflowError
    at Main.forever(Main.java:3)

Summary

Recursion is a method calling itself, with a smaller problem each time. Always have a base case, where it stops. Next, methods that take any number of arguments.

Key takeaways
  • Base case
  • Recursive case
  • StackOverflowError
Next up: Varargs — any number of arguments