- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive factorial method in Java
The factorial of any non-negative integer is basically the product of all the integers that are smaller than or equal to it. The factorial can be obtained using a recursive method.
A program that demonstrates this is given as follows:
Example
public class Demo { public static long fact(long n) { if (n <= 1) return 1; else return n * fact(n - 1); } public static void main(String args[]) { System.out.println("The factorial of 6 is: " + fact(6)); System.out.println("The factorial of 0 is: " + fact(0)); } }
Output
The factorial of 6 is: 720 The factorial of 0 is: 1
Now let us understand the above program.
The method fact() calculates the factorial of a number n. If n is less than or equal to 1, it returns 1. Otherwise it recursively calls itself and returns n * fact(n - 1). A code snippet which demonstrates this is as follows:
public static long fact(long n) { if (n <= 1) return 1; else return n * fact(n - 1); }
In main(), the method fact() is called with different values. A code snippet which demonstrates this is as follows:
public static void main(String args[]) { System.out.println("The factorial of 6 is: " + fact(6)); System.out.println("The factorial of 0 is: " + fact(0)); }
- Related Articles
- Recursive fibonacci method in Java
- How to write recursive Python Function to find factorial?
- Comparing the performance of recursive and looped factorial function in JavaScript
- Recursive Constructor Invocation in Java
- Factorial program in Java using recursion.
- What is a recursive method call in C#?
- Factorial program in Java without using recursion.
- Java Program for Binary Search (Recursive)
- Java Program for Recursive Bubble Sort
- Java Program for Recursive Insertion Sort
- Java Program to Find Factorial of a number
- factorial() in Python
- Java Program to Count trailing zeroes in factorial of a number
- Factorial recursion in JavaScript
- Calculate Factorial in Python

Advertisements