Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find the factorial of a number.

Java Code Example — OOP Programs

ADVERTISEMENT

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

  1. Create a class Test.
  2. Inside it, define a method factorial(int x) that returns an int.
  3. Inside the method, use a loop to multiply numbers from 1 to x and return the result.
  4. Create a separate class Demo with the main method.
  5. In main, read an integer from the user.
  6. Instantiate the Test class.
  7. 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 main method inside the primary class being executed.
  • By separating the logic (Test class) from the execution entry point (Demo class), we follow the Single Responsibility Principle.
  • The Test class 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)
ADVERTISEMENT