Java Program to find factorial of a number using class and object


In this program, You will learn how to find factorial of a number using class and object in Java.


3! = 1 * 2 * 3

4! = 1 * 2 * 3 * 4


Example: How to find factorial of a number using class and object in Java

Run it Now
import java.util.Scanner;

class Main {

    int fact(int a) {
        int i, f = 1;

        for (i = 1; i <= a; i++) {
            f = f * i;
        }

        return f;
    }

    public static void main(String args[]) {
        int a, f;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a Number :");
        a = sc.nextInt();

        Main ff = new Main();
        f = ff.fact(a);

        System.out.println("\nThe Factorial is :" + f);
    }
}

Output:

Enter a Number :4
The Factorial is :24