×

# Java program to calculate factorial of a number using recursion

Given a number, we have to calculate factorial of a number using recursion.
Submitted by Nidhi, on June 01, 2022

## Problem statement

In this program, we will read an integer number from the user and then we will calculate the factorial of the input number using recursion.

## Java program to calculate factorial of a number using recursion

The source code to calculate the factorial of a number using recursion is given below. The given program is compiled and executed successfully.

```// Java program to calculate factorial of a
// number using recursion

import java.util.*;

public class Main {
public static long getFactorial(int num) {
if (num == 1)
return 1;
return num * getFactorial(num - 1);
}

public static void main(String[] args) {
Scanner X = new Scanner(System.in);
int num = 0;
long fact = 0;

System.out.print("Enter Number: ");
num = X.nextInt();

fact = getFactorial(num);

System.out.printf("Factorial is: " + fact);
}
}
```

### Output

```Enter Number: 5
Factorial is: 120
```

## Explanation

In the above program, we imported the "java.util.*" package to use the Scanner class. Here, we created a public class Main. The Main class contains two static methods getFactorial(), main(). The getFactorial() is a recursive method that calculates the factorial of a given number using recursion and returns the result to the calling method.

The main() method is the entry point for the program. Here, we read an integer number from the user and called the getFactorial() method to get the factorial of the specified number and printed the result.