Find Factorial in Java

Beginner
⏱️ 8 min read
📚 Updated: May 2026
🎯 2 Code Examples
Recursion & loop

What you’ll learn

  • The definition of n! for n >= 0, including 0! = 1.
  • A recursive solution and an iterative solution in Java.
  • Overflow limits for long, input validation, and live preview.

Prerequisites

Methods, loops, recursion basics, and Java integer types.

  • Know that 0! = 1 and factorial is for nonnegative integers.
  • Use long for exact values only up to 20!.

Formal definition

0! = 1, and for n >= 1, n! = n * (n - 1)!.

5!

5 * 4 * 3 * 2 * 1 = 120

Intuition

5!120
Expand
5*4*3*2*1
n!Step
Rule
n * (n - 1)!

Takeaway: each step multiplies the previous factorial by the next integer, so values grow very fast.

Live preview

Compute exact factorial values for 0..20 (safe for Java long).

Live result
Press "Compute n!".

Algorithm

Goal: compute n! for nonnegative n.

1

Base case

If n <= 1, return 1.

2

Multiply down

Use recursion n * factorial(n-1) or loop from 2 to n.

📜 Pseudocode

Pseudocode
function factorial(n):  // assume n >= 0
    if n <= 1:
        return 1
    return n * factorial(n - 1)
1

Recursive factorial

Classic recursive approach with validation and long bound.

java
public class Main {
    static final int FACT_MAX_LONG = 20;

    static long factorialRecursive(int n) {
        if (n == 0 || n == 1) return 1L;
        return n * factorialRecursive(n - 1);
    }

    public static void main(String[] args) {
        int number = 5;

        if (number < 0) {
            System.out.println("Factorial is not defined for negative integers.");
            return;
        }
        if (number > FACT_MAX_LONG) {
            System.out.println("n too large for exact long in this demo (max " + FACT_MAX_LONG + ").");
            return;
        }

        long result = factorialRecursive(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }
}
📤 Output
Factorial of 5 is: 120
2

Iterative factorial

Same result with O(1) extra space.

java
public class Main {
    static final int FACT_MAX_LONG = 20;

    static long factorialIterative(int n) {
        long result = 1L;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        return result;
    }

    public static void main(String[] args) {
        int number = 5;

        if (number < 0) {
            System.out.println("Factorial is not defined for negative integers.");
            return;
        }
        if (number > FACT_MAX_LONG) {
            System.out.println("n too large for exact long in this demo (max " + FACT_MAX_LONG + ").");
            return;
        }

        System.out.println("Factorial of " + number + " is: " + factorialIterative(number));
    }
}
📤 Output
Factorial of 5 is: 120

Optimization and scaling

For large n: use BigInteger in Java because long overflows after 20!.

Iterative approach: avoids recursion stack growth while keeping the same O(n) work.

Interview tip: always mention input validation and overflow constraints.

🔄 Input / output examples

nn!
01
11
5120
202432902008176640000

Edge cases and pitfalls

Negative

n < 0

Factorial is undefined for negative integers in this tutorial context.

Overflow

n > 20

Exact value does not fit in Java long; use BigInteger.

Stack

Deep recursion

Recursive calls consume stack frames; iterative version is safer for bigger inputs.

⏱️ Time and space complexity

VersionTimeExtra space
RecursiveO(n)O(n)
IterativeO(n)O(1)

Summary

  • Definition: 0! = 1, n! = n * (n - 1)!.
  • Code choices: recursion is intuitive, iteration uses constant extra space.
  • Limit: Java long stores exact factorial values only through 20!.

❓ FAQ

For a nonnegative integer n, n! is the product from 1 to n. By definition, 0! = 1.
Because 0! and 1! are both 1. These base cases end recursion.
long can store exact factorial only up to 20!. 21! is larger than Long.MAX_VALUE.
Both use O(n) multiplications. Iterative uses O(1) extra space while recursion uses O(n) call stack.
Factorial is not defined for negative integers in this context, so validate n >= 0.
Computing n! takes O(n) time. Space is O(n) with recursion, O(1) with an iterative loop.
Did you know?

Stirling's approximation describes factorial growth: n! ~ sqrt(2*pi*n) * (n/e)^n. It helps estimate very large factorials when exact fixed-width integers overflow.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful