Calculate factorial of a number in Java using recursion

Carvia Tech | May 18, 2019 | 1 min read | 54 views | Java Coding Challenges

Factorial of a number is calculated using below formula:

factorial (n) = n x (n-1) x (n-2) ... 1

the factorial of a number is calculated by formula number * (number -1) till zero and since the value of factorial zero is 1, it acts as a base case in the recursive version of the factorial method.

Recusive function to calculate factorial
public class Factorial {
    public int factorial(int n) {
        if (n == 1)
            return 1;
        else {
            return n * factorial(n - 1);
Iterative approach for factorial
public int fact(int number) {
    int result = 1;
    while (number != 0) {
        result = result * number;
    return result;

Here we are using int to hold the result of multiplication, which can quickly overflow due to maximum limit an integer can hold. We can improve the above two programs to use BigInteger as discussed in the below article:

Java Coding Challenges:
  1. Check if the given string is palindrome
  2. Write a program to reverse a string using recursion in Java
  3. Find two numbers of which the product is maximum in an array
  4. How will you check if a given sentence is a pangram
  5. Java program to check if two strings are anagrams
  6. How to check if the given number is palindrome in Java
  7. Create anagram buckets from a given input array of words
See all articles in Java Coding Challenges
Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. SDET: JUnit interview questions for automation engineer
  3. Check if the given number is Armstrong Number in Java
  4. Write a program to reverse a string using recursion in Java
  5. Calculate Fibonacci Series in Java
  6. Commonly used Http methods in RESTful services
  7. How to reverse a number in Java

Find more on this topic:
SDET Interviews image
SDET Interviews

SDET Java Interview pattern and collection of questions covering SDET coding challenges, automation testing concepts, functional, api, integration, performance and security testing, junit5, testng, jmeter, selenium and rest assured

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info