Java Programming Examples Tutorial Index

Java Function Programs


This Java example code demonstrates a simple Java program to calculate factorial values using recursion and print the output to the screen. In this Java program, a function is defined that calls itself multiple times until the specified condition matches. This process is called Recursion, and the function is called the Recursive function.

Example:
public class Factorial {

    public static void main(String[] args) {
        //Variable definition and assignment
        int num = 5;

        //Call recursive function
        long factorial = multiplyNumbers(num);

        //Print the output
        System.out.println("Factorial of " + num + " = " + factorial);
    }

    public static long multiplyNumbers(int num)
    {
        if (num >= 1)
            return num * multiplyNumbers(num - 1);
        else
            return 1;
    }
}
Program Output:
Factorial of 5 = 120