Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📘 Lesson  ·  Lesson 51

Factorial using Recursion in Java

In this lesson: Find factorial in Java using recursion — base case, call stack dry run and output. Copy & run now. In Hindi & English.

What is recursion

Recursion is when a method calls itself to solve a smaller version of a problem. Factorial is the classic example, because n! can be written in terms of (n-1)!. Every recursion needs a base case — a simple situation that stops it.

💡 Recursion = a method that calls itself, with a base case to stop it.

Factorial as recursion

Factorial has a naturally recursive definition:

5! = 5 × 4!
4! = 4 × 3!
...
0! = 1   (the base case)

Each factorial is defined using a smaller factorial, all the way down to 0! = 1. That structure maps directly onto a recursive method.

The Java program

public class Factorial {
    static int factorial(int n) {
        if (n == 0)              // base case
            return 1;
        return n * factorial(n - 1);   // recursive call
    }
    public static void main(String[] args) {
        System.out.println(factorial(5));
    }
}
120

The method returns 1 when n is 0 (base case), otherwise it returns n times the factorial of n-1. Each call reduces n until it reaches 0.

Dry run

Dry Run — factorial(5) recursion
CallnBase case? (n==0)Return
factorial(5)5no5 * factorial(4)
 factorial(4)4no4 * factorial(3)
  factorial(3)3no3 * factorial(2)
   factorial(2)2no2 * factorial(1)
    factorial(1)1no1 * factorial(0)
     factorial(0)0yesreturn 1 (stops)
Multiplying back: 1→1→2→6→24→ 5*24 = 120
💡 Understand it this way

Each call waits for the smaller call to finish. When factorial(0) returns 1, the results multiply back up: 1, 1, 2, 6, 24, and finally 5×24 = 120.

The base case matters

// WRONG: no base case -> infinite recursion
static int bad(int n) {
    return n * bad(n - 1);   // never stops -> StackOverflowError
}

Without a base case, the method calls itself forever, filling the call stack until Java throws a StackOverflowError. Every recursion must have a stopping condition.

Loop vs recursion

  • Recursion — elegant, mirrors the maths, but uses call stack memory.
  • Loop — more efficient, no deep stack, better for large n.

Both give the same answer. Learn recursion for understanding; use a loop when performance matters.

Common mistakes

  • Missing base case. Causes infinite recursion and a StackOverflowError.
  • Wrong base case value. 0! = 1, not 0.
  • Not reducing n. Each call must move toward the base case.
  • Deep recursion on huge n. Very large n can overflow the stack — use a loop.

Summary

  • Recursion is a method calling itself on a smaller problem.
  • Factorial: n * factorial(n-1), base case 0! = 1.
  • The base case stops the recursion — never skip it.
  • Results multiply back up as the calls return.
  • Use a loop instead for large n or better performance.

Next, see recursion in Floyd's triangle, or compare with loops in Java loops.

Frequently Asked Questions

What is recursion in Java?
Recursion is when a method calls itself to solve a smaller version of the same problem. Each call works on a smaller input until it reaches a simple case (the base case) that stops the recursion.
What is a base case in recursion?
The base case is the condition that stops the recursion, so it does not call itself forever. For factorial, the base case is n == 0 returning 1. Without a base case, you get infinite recursion and a StackOverflowError.
How does recursive factorial work?
factorial(n) returns n * factorial(n-1), calling itself with a smaller n each time, down to factorial(0) which returns 1. Then the results multiply back up to the answer.
What is a StackOverflowError?
It is the error you get when recursion goes too deep — usually because the base case is missing or wrong, so the method keeps calling itself and fills up the call stack memory.
Is recursion or a loop better for factorial?
A loop is more efficient and avoids deep call stacks, so it is often preferred for factorial. Recursion is elegant and mirrors the maths, making it great for learning and for naturally recursive problems.
← Back to Java Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicBubble Sort Your progress: 51 / 61 (84%) · Lesson 52 / 61 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free