Java Program for Factorial

factorial java program
Reading Time: 7 minutes

Introduction:

The provided Java program is a simple factorial calculator that takes a non-negative integer as input from the user, calculates its factorial using recursion, and then displays the result. Factorial is the product of all positive integers up to a given number. The program ensures that the input is a non-negative integer and provides an error message if an invalid input is detected.

Explanation:

  1. Import Statement: The program starts by importing the Scanner class from the util package to facilitate user input.
  2. User Input: The main method prompts the user to enter a non-negative integer, which is then read using the Scanner
  3. Input Validation: The program checks if the entered integer is non-negative. If it is, the factorial is calculated; otherwise, an error message is displayed, and the program terminates.
  4. Factorial Calculation: The calculateFactorial method is a recursive function that computes the factorial of the input integer n. The base cases check if n is 0 or 1, in which case the factorial is 1. Otherwise, the factorial is calculated by multiplying n with the factorial of (n – 1).
  5. Display Result: If the input is valid, the program prints the calculated factorial for the entered integer.
  6. Scanner Closure: The Scanner is closed to release system resources.

Algorithm:

  1. Begin the program.
  2. Import the Scanner
  3. Create a Scanner object to read user input.
  4. Prompt the user to enter a non-negative integer.
  5. Read the entered integer.
  6. Check if the integer is non-negative.
    • If negative, display an error message and terminate the program.
    • If non-negative, proceed to the next step.
  7. Call the calculateFactorial method with the entered integer.
  8. The calculateFactorial method:
    • If n is 0 or 1, return 1.
    • Otherwise, return n * calculateFactorial(n – 1).
  9. Display the calculated factorial for the entered integer.
  10. Close the Scanner
  11. End the program.

Code:

				
					import java.util.Scanner;
public class FactorialCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a non-negative integer: ");
        int n = scanner.nextInt();
        if (n < 0) {
            System.out.println("Please enter a non-negative integer.");
        } else {
            long factorial = calculateFactorial(n);
            System.out.println("Factorial of " + n + " is: " + factorial);
        }
        scanner.close();
    }
    private static long calculateFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        } else {
            return n * calculateFactorial(n - 1);
        }
    }
}


				
			

Input:

				
					Enter a non-negative integer: 45
				
			

Output:

				
					Factorial of 45 is: -8797348664486920192
				
			

This program prompts the user to enter a non-negative integer and then calculates its factorial using a recursive method. The calculateFactorial method is a recursive function that computes the factorial of the given integer.

FAQ’s

  1. Q: Is it possible to see an example of a Java program for calculating the factorial of a number?
    • A: Absolutely! Check out this Java program for factorial, which takes a non-negative integer input and recursively calculates its factorial.
  2. Q: Can you share a Java program specifically designed for finding the factorial of a number?
    • A: Certainly! Here’s a Java program that prompts the user for a non-negative integer and then computes its factorial using a recursive approach.
  3. Q: How can I create a Java program for factorial calculation?
    • A: Creating a Java program for factorial is straightforward. You can input a non-negative integer, validate it, and then use a recursive method to calculate its factorial.
  4. Q: Is there a standard Java program to find the factorial of a number, or can it be customized based on requirements?
    • A: While there isn’t a single standard program, a typical Java program to find the factorial of a number involves user input, validation, and a recursive method for factorial calculation.
  5. Q: What’s the general structure of a factorial Java program, and how can I implement one myself?
    • A: A factorial Java program usually includes user input, validation, and a recursive method for factorial calculation. You can customize it based on your specific needs and preferences.