Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

Given a non-negative integer n, factorial is the product of all positive integers less than or equal to n.

In this quick tutorial, we’ll explore different ways to calculate factorial for a given number in Java.

2. Factorial for Numbers up to 20

2.1. Factorial Using a for Loop

Let’s see a basic factorial algorithm using a for loop:

public long factorialUsingForLoop(int n) {
    long fact = 1;
    for (int i = 2; i <= n; i++) {
        fact = fact * i;
    }
    return fact;
}

The above solution will work fine for numbers up to 20. But, if we try something bigger than 20, then it will fail because results would be too large to be fit into a long, causing an overflow.

Let’s see a few more, noting that each of these will only work for small numbers.

2.2. Factorial Using Java 8 Streams

We can also use the Java 8 Stream API to calculate factorials quite easily:

public long factorialUsingStreams(int n) {
    return LongStream.rangeClosed(1, n)
        .reduce(1, (long x, long y) -> x * y);
}

In this program, we first use LongStream to iterate through the numbers between 1 and n. We then used reduce(), which uses an identity value and accumulator function for the reduction step.

2.3. Factorial Using Recursion

And let’s see another example of a factorial program, this time using recursion:

public long factorialUsingRecursion(int n) {
    if (n <= 2) {
        return n;
    }
    return n * factorialUsingRecursion(n - 1);
}

2.4. Factorial Using Apache Commons Math

Apache Commons Math has a CombinatoricsUtils class with a static factorial method that we can use to calculate the factorial.

To include Apache Commons Math, we’ll add the commons-math3 dependency into our pom:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-math3</artifactId>
    <version>3.6.1</version>
</dependency>

Let’s see an example using the CombinatoricsUtils class:

public long factorialUsingApacheCommons(int n) {
    return CombinatoricsUtils.factorial(n);
}

Notice that its return type is long, just like our home-grown solutions.

That means here that if the computed value exceeds Long.MAX_VALUE, a MathArithmeticException is thrown.

To get any bigger, we are going to need a different return type.

3. Factorial for Numbers Greater Than 20

3.1. Factorial Using BigInteger

As discussed before, the long datatype can be used for factorials only for n <= 20.

For larger values of n, we can use the BigInteger class from the java.math package, which can hold values up to 2^Integer.MAX_VALUE:

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

3.2. Factorial Using Guava

Google’s Guava library also provides a utility method for calculating factorials for larger numbers.

To include the library, we can add its the guava dependency to our pom:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

Now, we can use the static factorial method from the BigIntegerMath class to calculate the factorial of a given number:

public BigInteger factorialUsingGuava(int n) {
    return BigIntegerMath.factorial(n);
}

4. Conclusion

In this article, we saw a few ways of calculating factorials using core Java as well as a couple of external libraries.

We first saw solutions using the long data type for calculating factorials of numbers up to 20. Then, we saw a couple of ways to use BigInteger for numbers greater than 20.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 4th December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW