You are here

Java program to find factorial

Java program to find factorial of a number: entered number is checked first if it is negative, then an error message is printed. You can also find factorial using recursion, in the code the variable fact is an integer so only factorial of small numbers will be correctly displayed, which fits in 4 bytes. For large numbers you can use long data type.

Java programming code

import java.util.Scanner;
class Factorial
   public static void main(String args[])
      int n, c, fact = 1;
      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(;
      n = in.nextInt();
      if (n < 0)
         System.out.println("Number should be non-negative.");
         for (c = 1; c <= n; c++)
            fact = fact*c;
         System.out.println("Factorial of "+n+" is = "+fact);

Download Factorial program class file.

Output of program:
Java factorial program output

Java program for calculating factorial of large numbers

Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and can't be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.

import java.util.Scanner;
import java.math.BigInteger;
class BigFactorial
  public static void main(String args[])
    int n, c;
    BigInteger inc = new BigInteger("1");
    BigInteger fact = new BigInteger("1");
    Scanner input = new Scanner(;
    System.out.println("Input an integer");
    n = input.nextInt();
    for (c = 1; c <= n; c++) {
      fact = fact.multiply(inc);
      inc = inc.add(BigInteger.ONE);
    System.out.println(n + "! = " + fact);

Download Big Factorial class file.

We run the Java program to calculate 100 factorial and the following output is obtained.

Input an integer
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000