Methods

Java Program to Find Factorial Using Recursion

A Java program to find the factorial of a number using recursion.

Problem Description

Write a Java program to find the factorial of a non-negative integer using recursion.

Code

FactorialRecursion.java
public class FactorialRecursion {
    public static void main(String[] args) {
        int num = 6;
        long factorial = multiplyNumbers(num);
        System.out.println("Factorial of " + num + " = " + factorial);
    }

    public static long multiplyNumbers(int num) {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}

Output

Factorial of 6 = 720

Explanation

  1. Recursion: multiplyNumbers calls itself.
  2. Base Case: When num is less than 1, return 1.
  3. Logic: n! = n * (n-1)!.