Java program to find factorial of a number using recursion

Here's a Java program to find the factorial of a number using recursion:

refer to:‮figi‬tidea.com
public class Main {
    public static void main(String[] args) {
        int number = 5;

        long factorial = factorial(number);

        System.out.println("Factorial of " + number + " is " + factorial);
    }

    public static long factorial(int n) {
        if (n == 0) {
            return 1;
        } else {
            return n * factorial(n - 1);
        }
    }
}

In this program, we first initialize an int variable number with the value 5.

We then call the factorial method, passing in number as an argument. This method returns the factorial of number.

The factorial method uses recursion to calculate the factorial of the input n. If n is 0, the method returns 1. Otherwise, it multiplies n by the factorial of n-1.

The output of this program will be:

Factorial of 5 is 120

You can replace 5 with any other integer value to calculate its factorial. Note that the factorial of a negative number is undefined, and the factorial of a non-negative number that is greater than 20 may exceed the maximum value that can be stored in a long variable.