Factorial Program in Java

In mathematics, the factorial of an integer is defined as the product of all positive integers less than or equal to the integer. Factorial of integer n is denoted by n!. For example, factorial of 5 is (5!) = 5 * 4 * 3 * 2 * 1 = 120.

Factorial Program in Java

The following example program in Java prints the factorial of a given integer. The program uses a simple loop to generate the factorial.

/* factorial example in java */
public class Factorial {

    public static void main(String[] args) {
        printFactorial(5);
    }
    
    public static void printFactorial(int n) {
        int factorial = 1;
        for(int i=1;i<=n;i++) {
            factorial = factorial * i;
        }
        System.out.println(factorial);
    }
}

 

Factorial Program in Java Using Recursion

The following Java example generates factorial of an integer using recursion.

/* factorial example program in java using recursion */
public class FactorialRecursion {
    public static void main(String[] args) {
        int factorial = getFactorial(5);
        System.out.println(factorial);
    }
    
    public static int getFactorial(int n) {
        if(n>1) {
            return n*getFactorial(n-1);
        }else {
            return 1;
        }
    }
}