Factorial of a Number Using Recursion in Java

At times, you might be required to calculate the factorial of a given number, so, in this article, we are going to learn about the simple program in Java, through which we can easily calculate the factorial of the given number. We will not only see the program but also the logic behind calculating the factorial of the given number.

Factorial of a Number Using Recursion in Java

You can easily do this program, provided that you already know how to calculate the factorial of the given number, and you know the basics of how to write a Java program.

In the given video, you can find an easy explanation and program to calculate the factorial of a given number using recursion.

Here is the Java Program to calculate the factorial of the given number using recursion-

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter a non-negative integer: “);
int n = scanner.nextInt();

if (n < 0) {
System.out.println(“Factorial not defined for negative numbers.”);
}

else {
long factorial = factorialCalculator(n);
System.out.println(“Factorial of ” + n + ” is ” + factorial);
}

scanner.close();
}

// Recursive function to calculate factorial
public static long factorialCalculator(int n) {
if (n == 0 || n == 1) {
return 1;
}

else {
return n * factorialCalculator(n – 1);
}
}
}

Program Output example 1 –
Enter a non-negative integer: 5
Factorial of 5 is 120

Program Output example 2 –
Enter a non-negative integer: 10
Factorial of 10 is 3628800