Java Program to find the factorial of a number.
Objective
Write a Java program to calculate the factorial of a number using a method defined in a separate class.
Algorithm / Approach
- Create a class
Test. - Inside it, define a method
factorial(int x)that returns anint. - Inside the method, use a loop to multiply numbers from 1 to
xand return the result. - Create a separate class
Demowith themainmethod. - In
main, read an integer from the user. - Instantiate the
Testclass. - Call the
factorial()method and print the returned value.
Test.java
import java.util.Scanner;
class Test {
public int factorial(int x) {
int f = 1;
for(int i = 1; i<=x; i++) {
f = f*i;
}
return f;
}
}
class Demo {
public static void main(String[] a)
{
Test t = new Test();
Scanner s=new Scanner(System.in);
System.out.print("Enter a Num: ");
int x = s.nextInt();
int fact = t.factorial(x);
System.out.print("Result = "+fact);
}
}
Expected Output
Enter a Num: 6 Result = 720
Explanation of the Program
- In Java, a program can consist of multiple classes. The JVM always looks for the
mainmethod inside the primary class being executed. - By separating the logic (
Testclass) from the execution entry point (Democlass), we follow the Single Responsibility Principle. - The
Testclass can now be reused by any other class that needs to calculate a factorial.
Complexity
Time Complexity
O(x) - The loop runs x times.
Space Complexity
O(1)