# 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

1. import java.util.Scanner;
2.
3. class Factorial
4. {
5.    public static void main(String args[])
6.    {
7.       int n, c, fact = 1;
8.
9.       System.out.println("Enter an integer to calculate it's factorial");
10.       Scanner in = new Scanner(System.in);
11.
12.       n = in.nextInt();
13.
14.       if (n < 0)
15.          System.out.println("Number should be non-negative.");
16.       else
17.       {
18.          for (c = 1; c <= n; c++)
19.             fact = fact*c;
20.
21.          System.out.println("Factorial of "+n+" is = "+fact);
22.       }
23.    }
24. }

Output of program:

## 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.

1. import java.util.Scanner;
2. import java.math.BigInteger;
3.
4. class BigFactorial
5. {
6.   public static void main(String args[])
7.   {
8.     int n, c;
9.     BigInteger inc = new BigInteger("1");
10.     BigInteger fact = new BigInteger("1");
11.
12.     Scanner input = new Scanner(System.in);
13.
14.     System.out.println("Input an integer");
15.     n = input.nextInt();
16.
17.     for (c = 1; c <= n; c++) {
18.       fact = fact.multiply(inc);