Basic java code

Calculating Factorial in Java Using Recursion

In this post, we’ll explore how to calculate the factorial of a non-negative integer using Java. Factorial, denoted as n!n!, is the product of all positive integers up to nn. For instance, 5!=5×4×3×2×1=1205! = 5 \times 4 \times 3 \times 2 \times 1 = 120.

The Code

Here’s a simple Java program that prompts the user to enter a non-negative integer and calculates its factorial using a recursive method.



import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner num = new Scanner(System.in);
       
        System.out.print("Enter a non-negative integer: ");
        int number = num.nextInt();
       
        if (number < 0) {
            System.out.print("Please enter a non-negative number.");
        } else {
            long fact = calcfact(number);
            System.out.print("The factorial of " + number + " is " + fact);
        }
       
        num.close(); // Close the scanner
    }

    public static long calcfact(int n) {
        if (n == 0) {
            return 1; // Base case: factorial of 0 is 1
        } else {
            return n * calcfact(n - 1); // Recursive case
        }
    }
}

Explanation of the Code

  1. Importing the Scanner Class:

    import java.util.Scanner;

    This line imports the Scanner class, which is used to read input from the user.

  2. Main Class:

    public class Factorial {

    The class is defined with the name Factorial.

  3. Main Method:

    public static void main(String[] args) {

    This is the entry point of the program. It executes the code inside it.

  4. Creating a Scanner Object:


    Scanner num = new Scanner(System.in);

    This creates a Scanner object named num to read input from the console.

  5. User Input:


    System.out.print("Enter a non-negative integer: "); int number = num.nextInt();

    The program prompts the user to enter a non-negative integer.

  6. Input Validation:


    if (number < 0) { System.out.print("Please enter a non-negative number."); }

    If the user enters a negative number, a message is displayed, and the program does not proceed to calculate the factorial.

  7. Calculating Factorial:


    long fact = calcfact(number);

    If the input is valid, the program calls the calcfact method to calculate the factorial.

  8. Recursive Method:


    public static long calcfact(int n) { if (n == 0) { return 1; // Base case } else { return n * calcfact(n - 1); // Recursive call } }
    • Base Case: If nn is 0, the method returns 1 (since 0!=10! = 1).
    • Recursive Case: If nn is greater than 0, it returns nn multiplied by the factorial of n1n - 1.
  9. Closing the Scanner:

    num.close();

    It’s a good practice to close the Scanner object to free up system resources.

Comments