Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconFactorial Program in Java | Java Program to Find Factorial

Factorial Program in Java | Java Program to Find Factorial

Last updated:
22nd Jun, 2023
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Factorial Program in Java | Java Program to Find Factorial

Introduction

Java is one of the popular languages. It has gained a lot of craze among the programmers because of its platform independence. Java proves itself flexible in web developers’ view and user-friendly in programmers because they can deploy an application developed in this programming language in all operating systems.

The object-oriented feature of Java provides many ways to reach the pristine code shore and offer good readability. Also, code reusability is simple in Java and avoids code duplication. Along with that, Java provides many predefined methods and libraries for a smooth workflow.

Now coming to our point, we will discuss the implementation of factorial of a number in Java. Many of you might know how to calculate the factorial of a number, but for the people who are new to the term, factorial lets quickly have a look at calculating the factorial of a number.

Check out our free courses to get an edge over the competition.

Ads of upGrad blog

The symbol denotes the factorial of a number “! “, so the factorial of an integer can denote by n!. And it is equal to the product of all numbers between 1 to n. For example, the factorial of 5 is 120 (1x2x3x4x5).

Factorial Program in Java and its Types

Factorial is a fundamental mathematical operation used in many algorithms and computations.Let’s start by writing a factorial program in Java using an iterative approach. The factorial of a non-negative integer n, denoted as n!, is the product of all positive integers less than or equal to n.

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

In this program, we take input from the user using the Scanner class. We initialize the factorial variable to 1 and then use a for loop to multiply all the numbers from 1 to the given number. Finally, we display the factorial.

Factorial Program in Java Script

Similarly, we can write a factorial program in Java Script using an iterative approach. JavaScript provides a concise syntax for such programs.

function factorial(number) {
    let factorial = 1;
    for (let i = 1; i <= number; i++) {
        factorial *= i;
    }
    return factorial;
}
let number = parseInt(prompt("Enter a number: "));
let result = factorial(number);
console.log(`Factorial of ${number} is: ${result}`);

In this JavaScript program, we define a function called factorial that takes a number as input. We then initialize the factorial variable to 1 and use a for loop to calculate the factorial. Finally, we display the factorial using the console.log() function.

Factorial Using Recursion in Java

Recursion is a powerful programming technique where a method calls itself to solve a problem. Let’s explore how we can calculate factorial using recursion in Java.

import java.util.Scanner;
public class FactorialProgram {
    public static int factorial(int number) {
        if (number == 0 || number == 1) {
            return 1;
        } else {
            return number * factorial(number - 1);
        }
    }
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        int result = factorial(number);
        System.out.println("Factorial of " + number + " is: " + result);
        scanner.close();
    }
}

In this program, we define a recursive function called factorial that takes a number as input. The base case is when the number is 0 or 1, where the factorial is always 1. For any other number, the factorial is calculated by multiplying the number with the factorial of the number minus one. This process continues until we reach the base case.

Therefore, we have explored three different ways to write a factorial program in Java and its variants: an iterative approach using a for loop, an iterative approach using Javascript, and a factorial using recursion in Java. Understanding how these programs work can help you create more efficient algorithms to solve complex problems.

Recursive Solution

Let us walk through a recursive java program!

import java.util.*;
public class UpGrad{
    public static int factorial(int n){
        if(n==1 || n==0)
            return 1;
        return n*factorial(n-1);
    }
 public static void main(String[] args) {
 Scanner sc=new Scanner(System.in);
 int n=sc.nextInt();
 System.out.print("factorial of "+n+" is "+factorial(n));
 }
}

In the above code, we’ve created a class and implemented a method factorial that expects an integer as a parameter and returns that number factorial. We have a base case that returns one if the given number is equal to 0 or 1 because factorial of 0 and 1 are 1.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

Later, we recursively call the factorial of the preceding numbers by multiplying the current number to the prior number factorial. Later we have a primary method and a scanner object instantiated in it. We read the integer n from user input and call the factorial way bypassing the user input as the parameter. And finally, we are printing the factorial onto the screen.

We can further minimize the factorial method’s size, which we’ve implemented in the above code. We can use a ternary operator to don’t even need an if block and finish the single line implementation. And here’s the code to do that.

public static int factorial(int n){
        return n>1?n*factorial(n-1):1;
    }
public static void main(String[] args) {
 Scanner sc=new Scanner(System.in);
 int n=sc.nextInt();
 System.out.print("factorial of "+n+" is "+factorial(n));
}

Check out upGrad’s Java Bootcamp.  

But few of the programmers prefer an iterative solution over a recursive solution. Because the execution flow is frequently interrupted in a recursive implementation, let us walk through an iterative solution to find a number factor.

Explore Our Software Development Free Courses

Iterative Solution

import java.util.*;
public class UpGrad
{
    public static int factorial(int n){
        int fact=1;
        for(int i=1;i<=n;i++)
            fact=fact*i;
        return fact;
    }
 public static void main(String[] args) {
 Scanner sc=new Scanner(System.in);
 int n=sc.nextInt();
 System.out.print("factorial of "+n+" is "+factorial(n));
 }
}

In the above code, we’ve implemented a method that computes the factorial of a number iteratively. This method expects an integer as a parameter and returns the factorial of that number. Inside that function, we’ve declared a variable and assigned it with value 1.

Then we are looping over the array from 1 to n and multiplying the number to the variable we declared; note that the product of n is also inclusive in factorial of a number. Then we are returning the computed factorial. Later we’ve written the primary method and similar work of reading the user input, calculating the factorial by calling the factorial method.

Also Read: Top Java Project & Ideas

Ads of upGrad blog

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Explore our Popular Software Engineering Courses

Conclusion

We have gone through a brief overview of the java features, reasons for java flexibility, reasons why Java is popular. And then, we’ve discussed how to calculate the factorial of a number. Then we’ve discussed a recursive solution to calculate the factorial of a number, also walked through another recursive solution that has an implementation using ternary operators. And then, we’ve discussed an iterative solution, such that people who prefer an iterative solution can utilize that implementation.

Now that you are aware of implementing the factorial program, recursively and iteratively, try building this code on your own by utilizing the Java OOP features. Try optimizing this solution further if possible and try figuring out the limitations of this implementation, if any.

If you’re interested to learn more about Java, full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development, which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.