Factorial of a Number in Java: All Methods with Examples

factorial of a number in Java

If you are looking for how to find the factorial of a number in Java, here is the quick answer: multiply all positive integers from 1 up to that number. In Java, you can implement this in just a few lines, for example, the factorial of 5 (written as 5!) is 5 × 4 × 3 × 2 × 1 = 120, and you can compute it using a simple for loop or recursion.

But there is more to it than that. Knowing the factorial of a number in Java deeply, across multiple approaches, is a skill that shows up in coding interviews, data science, algorithm design, and everyday Java development. Factorial calculation is also one of the most important problems included in number programs in Java, which help beginners build strong logical foundations.

In this blog, you will learn every major method to calculate factorial in Java with clean code examples, complexity analysis, and real-world context. Whether you are a beginner or brushing up for a technical interview, this guide has you covered.

What is a Factorial?

The factorial of a non-negative integer n is the product of all positive integers from 1 to n. It is represented using the exclamation mark: n!

Formula:

n! = n × (n-1) × (n-2) × ... × 2 × 1

Examples:

  • 3! = 3 × 2 × 1 = 6
  • 5! = 5 × 4 × 3 × 2 × 1 = 120
  • 10! = 3,628,800

Special Cases

  • 0! = 1 (by mathematical convention, needed for formulas involving permutations and combinations to work correctly)
  • 1! = 1
  • Factorial of negative numbers is undefined

Real-World Applications of Factorial

Real-World Applications of Factorial
  • Permutations and combinations in mathematics
  • Probability calculations
  • Algorithm design (e.g., brute force search over arrangements)
  • Dynamic programming and memoization problems
  • Compiler and language theory

Method 1: Factorial of a Number in Java Using For Loop

The for loop is the most straightforward and widely used method to calculate the factorial of a number in Java. It iterates from the given number down to 1, multiplying at each step.

Algorithm

  • Initialize a variable factorial = 1
  • Loop from i = n down to 1
  • Multiply factorial by i in each iteration
  • Print the result

Java Code

import java.util.Scanner;


public class FactorialForLoop {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        long factorial = 1;
        for (int i = 1; i <= n; i++) {
            factorial *= i;
        }
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}

Output

Enter a number: 5

Factorial of 5 is: 120

This is the most recommended method for beginners because it is easy to read, efficient, and avoids any risk of stack overflow.

Method 2: Factorial in Java Using While Loop

The while loop works exactly like the for loop but separates the initialization and increment outside the loop header. Use this when you want more explicit control over your loop variable.

Java Code

public class FactorialWhileLoop {
    public static void main(String[] args) {
        int n = 6;
        long factorial = 1;
        int i = 1;
        while (i <= n) {
            factorial *= i;
            i++;
        }
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}

    

Output

Factorial of 6 is: 720

Method 3: Factorial in Java Using Do-While Loop

The do-while loop guarantees the loop body executes at least once before checking the condition. This can be useful when you want to ensure the calculation runs even for edge case inputs.

Java Code

public class FactorialDoWhile {
    public static void main(String[] args) {
        int n = 4;
        long factorial = 1;
        int i = n;
        do {
            factorial *= i;
            i--;
        } while (i > 0);
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}

Output

Factorial of 4 is: 24

Note: For n = 0, handle separately as the do-while will compute 1 × 0 which is incorrect. Add a check: if (n == 0) factorial = 1;

Method 4: Factorial of a Number in Java Using Recursion

Recursion is one of the most popular interview topics when it comes to factorial of a number in Java. A recursive function calls itself with a smaller version of the problem until it hits a base case.

How Recursion Works for Factorial

The key idea: factorial(n) = n × factorial(n-1). This breaks the problem down step by step:

factorial(5) = 5 × factorial(4)

factorial(4) = 4 × factorial(3)

factorial(3) = 3 × factorial(2)

factorial(2) = 2 × factorial(1)

factorial(1) = 1  ← base case

Java Code

public class FactorialRecursion {
    public static long 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 of 5 is: " + factorial(5));
    }
}

Output

Factorial of 5 is: 120

Important: For very large inputs (e.g., n > 10,000), recursion risks a StackOverflowError. Use iteration for production code with large inputs.

Method 5: Factorial in Java Using Ternary Operator

The ternary operator offers a compact, single-line way to express the recursive factorial logic. It replaces the if-else block with a concise conditional expression.

Java Code

public class FactorialTernary {
    public static long factorial(int n) {
        return (n <= 1) ? 1 : n * factorial(n - 1);
    }
    public static void main(String[] args) {
        System.out.println("Factorial of 7 is: " + factorial(7));
    }
}

Output

Factorial of 7 is: 5040

This is functionally identical to the recursion approach — just written more compactly. Good for code golf or situations where brevity matters.

Method 6: Factorial in Java Using Memoization

Memoization stores previously computed results to avoid redundant calculations. While factorial itself does not have overlapping subproblems (unlike Fibonacci), memoization is useful when factorial(n) might be called multiple times in a program.

Java Code

import java.util.HashMap;
public class FactorialMemoization {
    static HashMap<Integer, Long> cache = new HashMap<>();


    public static long factorial(int n) {
        if (n <= 1) return 1;
        if (cache.containsKey(n)) return cache.get(n);
        long result = n * factorial(n - 1);
        cache.put(n, result);
        return result;
    }


    public static void main(String[] args) {
        System.out.println("Factorial of 10 is: " + factorial(10));
        System.out.println("Factorial of 8 is: " + factorial(8));  // from cache
    }
}

Output

Factorial of 10 is: 3628800

Factorial of 8 is: 40320

Time Complexity: O(n) first call, O(1) for repeated calls  |  Space Complexity: O(n)

Method 7: Factorial of Large Numbers in Java Using BigInteger

Standard int and long data types in Java overflow quickly for large factorials. For example, 21! already exceeds the range of long (which maxes out around 9.2 × 10^18). Java’s BigInteger class handles arbitrarily large integers without overflow.

When to Use BigInteger

  • When n > 20 and you need the exact result
  • In scientific, statistical, or financial calculations
  • In competitive programming problems involving large factorials

Java Code

import java.math.BigInteger;


public class FactorialBigInteger {
    public static BigInteger factorial(int n) {
        BigInteger result = BigInteger.ONE;
        for (int i = 2; i <= n; i++) {
            result = result.multiply(BigInteger.valueOf(i));
        }
        return result;
    }


    public static void main(String[] args) {
        System.out.println("Factorial of 25 is: " + factorial(25));
        System.out.println("Factorial of 50 is: " + factorial(50));
    }
}

Output

Factorial of 25 is: 15511210043330985984000000
Factorial of 50 is: 30414093201713378043612608166979581188299763898377856000000000000

Comparison of All Methods

Here is a quick reference to help you pick the right method for your use case:

MethodTime ComplexitySpace ComplexityBest Use Case
For LoopO(n)O(1)General / Beginner use
While LoopO(n)O(1)General use
Do-While LoopO(n)O(1)At-least-once execution
RecursionO(n)O(n)Interviews, clean code
Ternary OperatorO(n)O(n)Compact / concise code
MemoizationO(n)O(n)Repeated computations
BigIntegerO(n)O(n)Large numbers (>20!)

Common Mistakes to Avoid

common mistakes to avoid
  • Not handling negative input, always validate that n >= 0 before computing.
  • Using int instead of long, int overflows at 13!, use long (safe up to ~20!) or BigInteger for larger values.
  • Missing base case in recursion, forgetting if (n <= 1) return 1 causes infinite recursion and StackOverflowError.
  • Off-by-one errors in loops, make sure your loop runs from 1 to n (inclusive), not 0 to n-1.
  • Calling factorial on very large n with recursion, stack depth grows linearly, use iteration for large inputs.

Frequently Asked Questions (FAQ)

Q1. What is the factorial of 0 in Java?

0! = 1. This is a mathematical convention required for combinatorics formulas (like nCr) to work correctly when r = 0 or r = n.

Q2. Which is the best method to calculate factorial in Java?

For most general use, the for loop is the best choice — it is O(n) time, O(1) space, easy to read, and has no risk of stack overflow. Use recursion when writing clean, expressive code for interviews. Use BigInteger when dealing with n > 20.

Q3. How do you handle large factorials in Java?

Use Java’s java.math.BigInteger class. It supports numbers of arbitrary size and prevents overflow that occurs when using int or long for factorials above 20.

Q4. What is the difference between iterative and recursive factorial in Java?

Iterative (loop) factorial uses O(1) space and has no stack overflow risk. Recursive factorial is more elegant and closer to the mathematical definition, but uses O(n) stack space and can cause StackOverflowError for large inputs.

Q5. Can factorial be calculated for negative numbers in Java?

No. Factorial is only defined for non-negative integers (0, 1, 2, …). For negative inputs, your program should throw an exception or display an error message.

Q6. What is the factorial of 1 in Java?

1! = 1. This is the base case in most recursive implementations of the factorial of a number in Java.

Conclusion

The factorial of a number in Java can be implemented in several ways, from a simple for loop to advanced techniques using recursion, memoization, and BigInteger. Here is a quick recap:

  • For loop and while loop are best for beginners and general use (O(1) space).
  • Recursion and ternary operator are great for interviews and mathematical elegance.
  • Memoization optimizes programs that compute factorials repeatedly.
  • BigInteger is essential when working with large values of n (beyond 20).

Mastering the factorial of a number in Java is not just about one method — it is about understanding which tool to pick based on the situation. Practice writing each version from scratch, and you will build a strong foundation in loops, recursion, and Java’s standard library.