View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Factorial Program in Java

Updated on 23/04/20251,360 Views

Looking for a factorial program in Java programming language that's efficient and easy to understand? You've come to the right place. A factorial calculation is a fundamental operation in computer science and mathematics that multiplies a number by all positive integers below it.

For example, the factorial of 5 (written as 5!) is calculated as: 5! = 5 × 4 × 3 × 2 × 1 = 120

Java offers multiple approaches to implement factorial calculations, from simple loops to elegant recursive methods. This guide covers everything you need to master factorial programs in Java, with practical examples and real-world applications.

Curious about where Java can take you? Enroll in upGrad's Software Engineering course to unlock career opportunities in software development.

Factorial Program in Java Using For Loop

The for loop approach is straightforward and efficient for calculating factorials.

Problem Statement: Write a Java program that calculates the factorial of a user-provided number using a for loop.

public class FactorialUsingForLoop {
    public static void main(String[] args) {
        // Define the number to calculate factorial
        int number = 5;
        
        // Initialize factorial as 1
        long factorial = 1;
        
        // Calculate factorial using for loop
        for (int i = 1; i <= number; i++) {
            factorial *= i;  // Multiply factorial by each number
        }
        
        // Display the result
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output:

Factorial of 5 is: 120

This program uses a simple for loop to multiply numbers from 1 to n, efficiently calculating the factorial value.

Factorial Program in Java Using While Loop

The while loop offers an alternative approach that some developers prefer.

Problem Statement: Create a Java program to find the factorial of a number using a while loop.

public class FactorialUsingWhileLoop {
    public static void main(String[] args) {
        int number = 6;
        long factorial = 1;
        int i = 1;
        
        // Calculate factorial using while loop
        while (i <= number) {
            factorial *= i;  // Multiply factorial by current number
            i++;  // Increment counter
        }
        
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output:

Factorial of 6 is: 720

The while loop implementation provides the same result as the for loop but may be preferred in situations where the loop's continuation depends on multiple conditions.

Want to integrate your Java skills with cloud and DevOps? Explore the Professional Certificate Program in Cloud Computing and DevOps to boost your backend and deployment expertise.

Factorial Program in Java Using Recursion

Recursion offers an elegant solution for factorial calculation by breaking it down into smaller subproblems.

Problem Statement: Implement a Java program that calculates factorial using recursion. The recursive method will call itself with decreasing values until it reaches the base case.

public class FactorialUsingRecursion {
    public static void main(String[] args) {
        int number = 4;
        long result = calculateFactorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
    }
    
    // Recursive method to calculate factorial
    public static long calculateFactorial(int n) {
        // Base case: factorial of 0 or 1 is 1
        if (n == 0 || n == 1) {
            return 1;
        }
        // Recursive case: n! = n * (n-1)!
        return n * calculateFactorial(n - 1);
    }
}

Output:

Factorial of 4 is: 24

The recursive approach provides a concise and mathematically elegant solution, although it may consume more memory for large numbers due to the call stack.

Tech-savvy leaders with Java expertise are shaping the AI future. Join the Executive Programme in Generative AI by IIIT-B to explore strategic applications of AI.

Factorial Program in Java Using Scanner

In practical applications, we often need to accept user input. Let's implement a factorial program that uses the Scanner class.

Problem Statement: Develop a Java program that accepts a number from the user and calculates its factorial.

import java.util.Scanner;

public class FactorialUsingScanner {
    public static void main(String[] args) {
        // Create Scanner object for user input
        Scanner scanner = new Scanner(System.in);
        
        // Prompt user for input
        System.out.print("Enter a non-negative integer: ");
        int number = scanner.nextInt();
        
        // Close scanner to prevent resource leak
        scanner.close();
        
        // Calculate factorial
        long factorial = 1;
        for (int i = 1; i <= number; i++) {
            factorial *= i;
        }
        
        // Display result
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output (for input 7):

Enter a non-negative integer: 7
Factorial of 7 is: 5040

This implementation enhances user interaction by accepting dynamic input, making it suitable for real-world applications.

Real-World Application: Combination Calculator

Factorials are essential in combinatorial mathematics, particularly for calculating combinations and permutations.

Problem Statement: Create a Java program that calculates the number of ways to select k items from n items (combinations) using factorials.

import java.util.Scanner;

public class CombinationCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Get total items (n) and items to select (k)
        System.out.print("Enter total number of items (n): ");
        int n = scanner.nextInt();
        
        System.out.print("Enter number of items to select (k): ");
        int k = scanner.nextInt();
        
        scanner.close();
        
        // Calculate combination using factorial: C(n,k) = n! / (k! * (n-k)!)
        long combination = factorial(n) / (factorial(k) * factorial(n - k));
        
        System.out.println("Number of ways to select " + k + " items from " + n + " items: " + combination);
    }
    
    // Method to calculate factorial
    public static long factorial(int num) {
        long result = 1;
        for (int i = 1; i <= num; i++) {
            result *= i;
        }
        return result;
    }
}

Output (for n=8, k=3):

Enter total number of items (n): 8
Enter number of items to select (k): 3
Number of ways to select 3 items from 8 items: 56

This real-world example demonstrates how factorial calculations are used in combination problems, such as determining lottery odds or selecting committee members from a group.

Handling Edge Cases

Proper factorial programs should handle edge cases like negative numbers and overflow.

Problem Statement: Create a robust factorial program that handles negative inputs and prevents overflow for large numbers.

import java.util.Scanner;
import java.math.BigInteger;

public class RobustFactorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.print("Enter a non-negative integer: ");
        int number = scanner.nextInt();
        scanner.close();
        
        try {
            BigInteger factorial = calculateFactorial(number);
            System.out.println("Factorial of " + number + " is: " + factorial);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        }
    }
    
    // Calculate factorial using BigInteger to handle large results
    public static BigInteger calculateFactorial(int n) {
        // Check for negative input
        if (n < 0) {
            throw new IllegalArgumentException("Factorial is not defined for negative numbers");
        }
        
        BigInteger result = BigInteger.ONE;
        
        // Calculate factorial
        for (int i = 1; i <= n; i++) {
            result = result.multiply(BigInteger.valueOf(i));
        }
        
        return result;
    }
}

Output (for input 20):

Enter a non-negative integer: 20
Factorial of 20 is: 2432902008176640000

This implementation handles two critical edge cases: negative inputs and large factorials that would overflow traditional integer types.

Conclusion

Creating a factorial program in Java is simpler than you might think. You can use for loops when you want something straightforward and fast. While loops work just as well if that's your preferred loop style. If you like elegant mathematical solutions, recursion is your friend, though it uses more memory.

When coding factorial programs for real applications, don't forget about edge cases. Negative numbers will cause errors, so check for them. For big numbers like 20!, use BigInteger to avoid overflow problems that happen with regular int values.

Factorial programs in Java are not just coding exercises - they're useful in statistics, combinations, and many scientific calculations. Whether you're a student learning Java fundamentals or a developer building scientific applications, mastering factorial implementations will strengthen your programming skills.

Remember that the factorial program in Java using recursion might look cleaner, but the factorial program in Java using for loop or while loop typically performs better for larger numbers. Choose your approach based on your specific needs.

FAQs

1. What is the factorial of zero in Java programs?

The factorial of zero is defined as 1 in mathematics and Java programs. This is a special case that's important to handle in your factorial program in Java. Many beginners forget this edge case, which can cause unexpected results in calculations that involve factorials of small numbers.

2. Can factorial programs handle negative numbers?

No, factorial is not defined for negative numbers in mathematics. When creating a factorial program in Java, you should include validation to check for negative inputs. Your program should either throw an exception or return an error message when users try to calculate the factorial of a negative number.

3. Why does my factorial program overflow for large inputs?

Standard Java integer types have size limits. The int type can only hold values up to about 2 billion, while long extends to about 9 quintillion. When calculating factorials, these limits are reached quickly (12! for int, 20! for long). Using a factorial program in Java with BigInteger solves this overflow problem for arbitrarily large numbers.

4. Is recursive factorial calculation more efficient than loops?

No, loops are generally more efficient as they avoid call stack overhead. A factorial program in Java using recursion needs to store each function call on the stack, consuming extra memory. For large inputs, this can even cause stack overflow errors. The factorial program in Java using for loop or while loop avoids this problem entirely by using constant memory.

5. What are common applications of factorial calculations?

Combinations, permutations, probability calculations, and statistical analysis frequently use factorials. Many scientific fields rely on factorial calculations, including combinatorial mathematics, probability theory, and statistical mechanics. Your factorial program in Java might be used to calculate lottery odds, possible arrangements, or even in machine learning algorithms for certain probability distributions.

6. How do I optimize factorial calculation for better performance?

Use loops instead of recursion and implement memoization for repeated calculations. A factorial program in Java using for loop is typically the most efficient approach. For applications that calculate many factorials, consider pre-computing common values (0! through 20!) and storing them in an array. This approach trades memory for speed, significantly improving performance for repeated calculations.

7. Can I calculate factorials of decimal numbers in Java?

Standard factorial is defined only for integers. For decimals, use the gamma function. The mathematical relationship is: Γ(n+1) = n! for positive integers. A factorial program in Java can be extended to handle decimal inputs by implementing the gamma function using numerical methods. This is useful in advanced statistical and scientific applications.

8. What's the largest factorial I can calculate using int in Java?

The largest factorial that fits in an int is 12! (479,001,600). The factorial program in Java must switch to long for values up to 20!, and BigInteger for larger values. Understanding these limits is crucial when designing programs that handle mathematical calculations, especially in scientific or engineering applications.

9. How do I debug my factorial program in Java?

Add print statements to trace execution flow and variable values at each iteration. When troubleshooting a factorial program in Java using recursion, print the current input value and return value for each recursive call. For loop-based implementations, print the current multiplier and running product. This helps identify exactly where and why issues occur.

10. Can I use a ternary operator for factorial calculation?

Yes, you can use ternary operators for recursive implementations in a single line. A factorial program in Java using recursion can be written concisely as: return (n <= 1) ? 1 : n * calculateFactorial(n-1);. This makes the code more compact but might be harder to read for beginners. For production code, prioritize readability over brevity unless performance is critical.

11. Why is factorial program in Java a common programming exercise?

It teaches loops, recursion, and handling edge cases in a simple mathematical context. The factorial program in Java appears in many programming courses because it demonstrates key programming concepts clearly. It shows both iterative and recursive approaches to the same problem, illustrates algorithm efficiency considerations, and introduces edge case handling—all valuable skills for new programmers.

12. How do I convert my factorial program to handle BigInteger inputs?

Replace primitive type parameters with BigInteger and use multiply() instead of * operator. When upgrading your factorial program in Java to handle very large numbers, you'll need to change your loop structure slightly. Initialize your result variable with BigInteger.ONE, and use the multiply() method for calculations: result = result.multiply(BigInteger.valueOf(i));. This approach removes the upper limit on factorial size.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.