# Java Program to calculate the factorial of a number

If you have just started learning Java and want to make Java Program to calculate the factorial. Shout coders have come up with two methods to calculate the factorial of a number.

So, if you are a pure beginner and want to learn the basics of java and want to install IDE on your Windows PC. Please read this: Introduction and Installation of Java on Windows.

Also, you should try the basic program of Program to add two numbers in Java.

## What is the Factorial of a Number?

Factorial of a number is the multiplication of all the numbers from 1 to the number itself.

**Example of Factorial of a Number – **Factorial of 6! is 1*2*3*4*5*6 = 720. So, you can see that it is the multiplication of all the numbers from 1 to number itself.

There are two types of approaches to the problem. The recursion approach is mostly used but can cause errors too.

- Loop Method
- Recursive Method

### Method 1: Loop Method –

In this method, we will run a loop from 1 and will multiply all the variables until the number itself.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class JavaExample { public static void main(String[] args) { //We will find the factorial of this number int number = 5; long fact = 1; int i = 1; while(i<=number) { fact = fact * i; i++; } System.out.println("Factorial of "+number+" is: "+fact); } } |

**Output – **Enter the number for factorial: 5 Factorial of the number is: 120

### Method 2: Recursive Method –

In this, we will make a function and will call it again and again until we will get the factorial of the number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class FactorialExample2{ static int factorial(int n){ if (n == 0) return 1; else return(n * factorial(n-1)); } public static void main(String args[]){ int i,fact=1; int number=3;// the number to calculate factorial fact = factorial(number); System.out.println("Factorial of "+number+" is: "+fact); } } |

**The output of the Program** – 3 Factorial of 3 is

Do not have the IDE to run the Java program, now you can run the Java Program on online IDE here.

## Frequently Asked Questions

**Is java a platform-independent language?**

Yes, java is a platform-independent language. The program written in Windows can be executed in Linux or Mac.

**What is the factorial of 0?**

The factorial of 0 is 1. For more, you have to go in deep mathematics.

**Is it an important program from an exam point of view?**

Yes, this is very important because it is a very important example of recursion.

**What is recursion?**

When a function calls himself until a condition is made, It is called recursion.