Java Basic Examples

Calculate factorial of a Number in Java Example

This example shows how to calculate factorial of a number in Java. This example also shows how to calculate factorial using for loop (non-recursive) or using recursion and calculating factorial for large numbers using BigInteger class.

What is factorial of a number?

Definition of factorial from Wikipedia,

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n.

In mathematics, a product is the result of multiplying.

For example, factorial of 4 (denoted by 4!) is 4 x 3 x 2 x 1 = 24.

How to calculate factorial of a number in Java?

Factorial of a number can be calculated in two ways, using for loop (non-recursive) method or using recursion

Calculate factorial using for loop

Factorial of a number can be calculated using for loop as given in below example.

Output

Calculate factorial using recursion

Factorial of a number can be calculated using recursive method as given below.

Output

How to calculate factorial of large numbers?

Let’s try to calculate factorial of 50 using the above program.

Output

Result is 0. How that happened? Well, factorial of 50 has 12 zeros at the end which is more than an int can hold (int is 32 bit signed value in Java) so converting it to int value gives us zero.

In order to calculate factorial of a large number we need to use BigInteger as given below.

Output

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: