Java Program to Find Factorial of a Number

Factorial is an important concept in mathematics and programming. In Java, it is commonly used to demonstrate loops and iterative logic.

In this tutorial, we will create a simple Java program that calculates the factorial of a given number using a loop.

By the end of this guide, you will understand how factorial works and how to implement it in Java using iterative logic.

Concept Overview

The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n.

For example, 5! = 5 × 4 × 3 × 2 × 1 = 120.

In Java, we can calculate factorial using loops such as for loop or while loop.

Program

Java
import java.util.Scanner;

public class FactorialNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int num = sc.nextInt();

        long factorial = 1;

        for (int i = 1; i <= num; i++) {
            factorial *= i;
        }

        System.out.println("Factorial of " + num + " is: " + factorial);
    }
}

Output

TEXT
Enter a number: 5
Factorial of 5 is: 120

Detailed Explanation

The program begins by importing the Scanner class to take user input.

Inside the main() method, a Scanner object is created to read the number from the user.

A variable factorial is initialized with value 1 because factorial multiplication starts from 1.

A for loop runs from 1 to the entered number and multiplies each value with factorial.

Finally, the result is displayed using System.out.println().

Example Walkthrough

Let us consider an example where the user enters 5.

The program performs: 1 × 2 × 3 × 4 × 5 = 120.

The output is displayed as 'Factorial of 5 is: 120'.

Applications

Factorial is widely used in mathematics, permutations and combinations, probability, and algorithm design.

It is also used in recursion problems and performance analysis in computer science.

Advantages of This Approach

This program is simple and helps beginners understand loops and iteration.

It demonstrates how repeated multiplication works in Java.

The logic can be easily modified for recursive implementations.

Limitations

The program does not handle negative numbers, as factorial is undefined for them.

Large inputs may cause overflow since factorial values grow very quickly.

Improvements You Can Make

You can add input validation to reject negative numbers.

You can implement factorial using recursion instead of loops.

You can also optimize it using memoization for repeated calculations.

This Java program provides a clear understanding of factorial calculation and loop usage. Mastering it helps build strong programming fundamentals.