Factorial Program in Java Using Loop and Recursion
In this tutorial, we'll learn how to calculate the factorial of a number using both loop and recursion in Java. This is one of the most common questions in Java interviews and coding challenges.
What is Factorial?
The factorial of a number n is the product of all positive integers less than or equal to n. It's represented by n!
Example:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
- 3! = 3 × 2 × 1 = 6
1️⃣ Factorial Using Loop
public class FactorialLoop {
public static void main(String[] args) {
int number = 5;
long fact = 1;
for(int i = 1; i <= number; i++) {
fact *= i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
2️⃣ Factorial Using Recursion
public class FactorialRecursion {
public static void main(String[] args) {
int number = 5;
long result = factorial(number);
System.out.println("Factorial of " + number + " is: " + result);
}
static long factorial(int n) {
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
}
🧠Interview Tip
Interviewers often ask for both loop and recursive versions. Make sure you understand the stack behavior in recursion.
✅ Output
Factorial of 5 is: 120
📌 Conclusion
We have seen how to write factorial programs in Java using both loops and recursion. These examples are helpful in improving your Java logic and preparing for interviews.