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.

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("Factorial is:" + f);
    }
}

Output:

Enter a number:4
Factorial is:24