This is one of the most frequently asked questions in any java interview:

"How do you calculate a factorial in java using recursing?"

I have faced in some of my interviews. Let's read a basic example below with source code, which will help you answer this question.

Let's define an algorithm which solves our problem, The factorial of any number 'n' is n!. This can be also written as n*(n-1) !

The below method is a self explanatory and easy to use. I  have given proper comments about the logic.

 

 

/**
This function calculates factorial of any given numnber. You can use this
Method in any Java Main Class by passing an input numnber.

Author: www.JavaGenious.com

*/

public static int calculateFactorial(int numb) {

//Return -1 for any negative number
if (numb < 0) {
 return -1;
 }
 
//The factorial of zero is 1
if (numb == 0) {
return 1;
}

//The factorial of 2 is 2
if (numb <= 2) {
return numb;
}

// This is a recursive step
 return (numb * factorial(numb - 1));
 
}

Enter your email address:

Delivered by FeedBurner



Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)