Java Program to find factorial of number in Java - Example Tutorial

How to find the factorial of a number in Java on both recursive and iterative way is a common Java interview question mostly asked at fresher level. It’s not just popular on Java interview but also on other programming languages like C or C++. It's also famous  In our last article we have seen how to check if a number is prime or not and in this Java programming tutorial we will see a simple Java program to find factorial of a number in Java by using recursion and iteration. The Same program can also be used to print factorial of any number or printing a range of factorial as well. Let’s talk about logic, the factorial of a number is calculated by formula number*(number -1) till zero and since the value of factorial zero is 1, it acts as a base case in the recursive version of the factorial method. the logic to find the factorial of a number is encapsulated inside factorial(int number) and fact(int number) method.

This Java programming tutorial is in next with my earlier tutorial for beginners like Java Program to reverse String in Java with recursion , Java program to free memory in java and recently  how to read and write to a text file in Java etc if you haven’t read them you may find them interesting and useful.

How to find factorial of number in Java using recursion and iteration :
In this section, we will see complete code example of Java program to calculate factorial of a number in both recursive and iterative way. If you look at closely you will find that recursive solution of calculating factorial is much easier to write and pretty intuitive to read as it represent formula number*(number -1).

Any way recursion should only be limited for educational purpose as it is always subject to stack overflow error if recursion is too deep. Calculating factorial of a number is also a good programming question to exercise for anyone who is just started learning to program. Anyway here is example of Java program to find factorial of a number :

/**
* Simple Java program to find the factorial of a number using recursion and iteration.
* Iteration will use for loop while recursion will call method itself
*/

public class FactorialInJava{

public static void main(String args[]) {

//finding factorial of a number in Java using recursion - Example
System.out.println("factorial of 5 using recursion in Java is: " + factorial(5));

//finding factorial of a number in Java using Iteration - Example
System.out.println("factorial of 6 using iteration in Java is: " + fact(6));
}

/*
* Java program example to find factorial of a number using recursion
* @return factorial of number
*/

public static int factorial(int number){
//base case
if(number == 0){
return 1;
}
return number*factorial(number -1); //is this tail-recursion?
}

/*
* Java program example to calculate factorial using while loop or iteration
* @return factorial of number
*/

public static int fact(int number){
int result = 1;
while(number != 0){
result = result*number;
number--;
}

return result;
}
}

Output:
factorial of 5 using recursion in Java is: 120
factorial of 6 using iteration in Java is: 720

That's all on how to calculate or find the factorial of a number in Java. Both iterative and recursive version of factorial can be used to calculate factorials but beware of StackOverFlowError if a larger number is passed to recursive version of the factorial method in Java.

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures and Algorithms: Deep Dive Using Java
Algorithms and Data Structures - Part 1 and 2

Anonymous said...

Just for the sake of completeness (which you undoubtedly know):

/**
* Tail recursive factorial.
*/
public static long factail(int number, long result) throws Exception {
if (number == 0) {
throw new Exception("result: " + result);
}
return factail(number - 1, result * number);
}

Of course, JVMs do not (like functional language interpreters or compilers) usually optimize for tail recursion, as the stack trace shows.

Anonymous said...

Sorry, forgot to add in the last post that you should call the auxiliary with result = 1.

public static long factorial(int number) throws Exception {
return factail(number, 1);
}

private static long factail(int number, long result) throws Exception {
if (number == 0) {
throw new Exception("result: " + result);
}
return factail(number - 1, result * number);
}

Anonymous said...

Indeed writing program to calculate factorial is good example for learning recursion. by the way is it tail recursive ?

Anonymous said...

At what point does this break down, because I've tested both methods incrementally up to 16 and they both give the same result (2004189184), but if you use 17 as the number then what you get back is a negative result, which cannot be correct (-288522240).

Why does this happen?

Anonymous said...

I think factorial program is not the best to understand recursion. The best way to understand recursion is to call a function twice i.e.
recursive()
{
System.out.println("Hello");
}
calling()
{
recursive();
recursive();
}
If you understand this then you probably know how recursion works.

Farruh Atabaev said...

I'd do it like this...

public static Integer factorial(int number) {
if (number == 1) {
System.out.println("Factorial ended");
return 1;
} else {
return number*factorial(number-1);
}
}

Anonymous said...

Could you write a program to calculate factorial but condition being you call the recursive function within a for loop

Anonymous said...

I do want to point out the question above regarding the negative result when retrieving the factorial for 17. This is because the primitive int is being used. To get around this then it is advised to use the BigInteger Object type.

Олег Александров said...

What kind of cache did you mean, when said this:
Since factorial of a number is equal to number multiplied by factorial of previous number, you can cache those value instead of recalculating them, this will impress your interviewer a bit. See the solution for full code example.

Javin Paul said...

Hi, I mean you can cache factorials instead of calculating again e.g. factorial(6) = 6* factorial(5), instead of calculating factorial(5), you can replace with 120. You can use any cache e.g. in memory, disk base or cloud based, upto you. simplest is a in memory HashMap cache.

Олег Александров said...

IMHO, it happens implicitly, isn't it?

Javin Paul said...

Sorry, didn't get you. If you don't store already calculated value they will be lost, you need to memoization technique, which is also popular in calculating fibonacci series.

Unknown said...

public class Fact{

public static void main(String[] args)
{
System.out.println(factorial(5));
}
public static int factorial(int n)
{
if(n==0||n==1)
return 1;

return factorial(n-1)*n;
}
}