Java Factorial Program

Introduction

The Factorial of a positive integer is the product of all positive integers from 1 to that number. It is represented by the exclamation mark (!).

For example:


5! = 5 × 4 × 3 × 2 × 1 = 120
4! = 4 × 3 × 2 × 1 = 24
3! = 3 × 2 × 1 = 6

Special cases:


0! = 1
1! = 1

The factorial concept is widely used in mathematics, probability, statistics, combinatorics, algorithms, and computer science.

The Java Factorial program is one of the most common interview questions because it helps beginners understand loops, recursion, methods, and arithmetic operations.

In this tutorial, you’ll learn different ways to calculate the factorial of a number in Java.

Java Program to Find Factorial Using a For Loop


public class Factorial {
    public static void main(String[] args) {
        int number = 5;
        long factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        System.out.println("Factorial of " + number + " = " + factorial);
    }
}

Output

Factorial of 5 = 120

How the Program Works?

Let's understand the logic step by step.

Step 1: Declare the Number


int number = 5;

This is the number whose factorial will be calculated.

Step 2: Initialize the Result


long factorial = 1;

The factorial starts with 1 because multiplying by 1 does not change the result.

Step 3: Run the Loop


for (int i = 1; i <= number; i++)

The loop runs from 1 to the given number.

Step 4: Multiply the Numbers


factorial *= i;

Calculation:

Iteration Factorial
1 1 × 1 = 1
2 1 × 2 = 2
3 2 × 3 = 6
4 6 × 4 = 24
5 24 × 5 = 120

Step 5: Display the Result


System.out.println("Factorial of " + number + " = " + factorial);

Output:

Factorial of 5 = 120

Java Program Using While Loop


public class Factorial {
    public static void main(String[] args) {
        int number = 5;
        long factorial = 1;
        while (number > 0) {
            factorial *= number;
            number--;
        }
        System.out.println("Factorial = " + factorial);
    }
}

Output

Factorial = 120

Java Program Using Recursion

Recursion is another popular method for calculating factorial.


public class Factorial {
    static long factorial(int number) {
        if (number == 0 || number == 1)
            return 1;
        return number * factorial(number - 1);
    }
    public static void main(String[] args) {
        int number = 5;
        System.out.println("Factorial = " + factorial(number));
    }
}

Output

Factorial = 120

How Recursion Works?

For 5!:


factorial(5)
= 5 × factorial(4)
= 5 × 4 × factorial(3)
= 5 × 4 × 3 × factorial(2)
= 5 × 4 × 3 × 2 × factorial(1)
= 5 × 4 × 3 × 2 × 1
= 120

Java Program Using User Input


import java.util.Scanner;
public class Factorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        long factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        System.out.println("Factorial = " + factorial);
        scanner.close();
    }
}

Output

Enter a number: 6
Factorial = 720

Algorithm

  1. Read the number.
  2. Initialize the factorial as 1.
  3. Multiply the factorial by each number from 1 to the given number.
  4. Store the result.
  5. Display the factorial.

Flowchart Logic


 Start
   │
Read Number
   │
factorial = 1
   │
Multiply factorial by each number
   │
Loop Until Number Ends
   │
Display Result
   │
  End

Time Complexity

Using Loop


O(n)

The loop executes exactly n times.

Using Recursion


O(n)

The recursive function is called n times.

Space Complexity

Loop Approach


O(1)

Only a few variables are used.

Recursive Approach


O(n)

Recursive calls consume stack memory.

Common Mistakes

1. Initializing Factorial with Zero

Incorrect:


long factorial = 0;

Any number multiplied by 0 remains 0.

Correct:


long factorial = 1;

2. Incorrect Loop Condition

Incorrect:


for(int i = 0; i <= number; i++)

This causes multiplication by zero.

Correct:


for(int i = 1; i <= number; i++)

3. Forgetting the Base Case in Recursion

Incorrect:


return number * factorial(number - 1);

Without a base case, recursion never stops.

Correct:


if(number == 0 || number == 1)
    return 1;

4. Using int for Large Factorials

Factorial values grow very quickly.

Example:


20! = 2,432,902,008,176,640,000

Use long for larger values, or BigInteger when calculating very large factorials.

5. Accepting Negative Numbers

Factorials are defined only for non-negative integers.

Always validate user input.

Example:


if(number < 0) {
    System.out.println("Factorial is not defined for negative numbers.");
    return;
}

Applications of Factorial

Factorials are used in many real-world applications, including:

  • Mathematics
  • Probability
  • Statistics
  • Permutations and combinations
  • Dynamic programming
  • Cryptography
  • Scientific computing
  • Machine learning algorithms

Summary

The Java Factorial program is one of the most important beginner-level programming examples. It teaches essential programming concepts such as loops, recursion, arithmetic operations, methods, and user input handling.

For most practical applications, the iterative (loop-based) approach is recommended because it is efficient and uses constant memory. The recursive approach is useful for learning recursion but may lead to stack overflow for very large inputs.

Related Java Tutorials