In this post we’ll see a Java program to find the factorial of a number.

Factorial of a non-negative integer n is product of all positive integers less than or equal to n.

**For example** – 5! = 5 X 4 X 3 X 2 X 1 = 120

#### Factorial program in Java

Factorial program in Java can be written as both iterative as well as recursive solution. In this post both of the solutions are given.

#### Factorial program using iteration

In iterative logic you can start a for loop with the entered number and decrease it by 1 in each iteration. What you need is the multiplication of all the numbers in the loop.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Scanner; public class Factorial { public static void main(String[] args) { // Input from user Scanner input = new Scanner(System.in); System.out.println("Enter a number: "); int number = input.nextInt(); int factorial = 1; for(int i = number; i >= 1; i--){ factorial = factorial * i; } System.out.println("Factorial of " + number + " is " + factorial); } } |

__Output__

1 2 3 |
Enter a number: 5 Factorial of 5 is 120 |

#### Factorial program in Java using recursion

In the recursive logic to write factorial Java program, you need to call the same method recursively passing the (number – 1) as parameter every time until the base case (number = 1) is reached.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import java.util.Scanner; public class Factorial { public static void main(String[] args) { // Input from user Scanner input = new Scanner(System.in); System.out.println("Enter a number: "); int number = input.nextInt(); int factorial = calculateFactorial(number); System.out.println("Factorial of " + number + " is " + factorial); } // Factorial using recursion private static int calculateFactorial(int num){ // base case if(num == 1){ return 1; }else{ return num * calculateFactorial(num - 1); } } } |

__Output__

1 2 3 |
Enter a number: 8 Factorial of 8 is 40320 |

That’s all for the topic **Factorial Program in Java**. If something is missing or you have something to share about the topic please write a comment.

**You may also like**

- Display Armstrong Numbers in Java
- Java Program to Check Whether Number Prime or Not
- Java Program to Check if The Given Strings Are Anagram or Not
- Why wait(), notify() And notifyAll() Methods Are in Object Class
- Overview of Exception Handling in Java
- What is Hadoop