Find Factorial of a Number in Java

Factorial is the product of all positive integers less than or equal to a given positive integer. For example, for the given number 5, the factorial is 120 (5*4*3*2*1). Let’s see how we can find the factorial of a number in Java.

Below is an example program that uses a recursive method to find the factorial of a given number. Recursion in Java is the process in which the method calls itself.

Example

public class Test {

  public static void main(String[] args) {

    System.out.println(factorial(5));

  }

  static int factorial(int num) {
    if (num == 1) {
      return 1;
    } else
      return (num * factorial(num - 1));
  }
}
Output: 120
 
This code defines a static method named “factorial” that takes an integer argument and calculates the factorial of that number using recursion. The method checks if the input number is 1 and returns 1. Otherwise, it returns the input number multiplied by the factorial of input number -1.
 
Another way of finding the factorial of a number in Java would be using the for loop:
public class Test {

  public static void main(String[] args) {

    int n = 5, factorial = 1; // starts from 1

    for (int i = 1; i <= n; i++) {
      factorial = factorial * i;
    }

    System.out.println(factorial);
  }
}
Output: 120
 
That’s it!

Leave a Reply

Your email address will not be published. Required fields are marked *