Factorial Program in Java - Recursive & Iterative
Calculate factorial of a number in Java. Examples using for loop and recursion.
Last updated: 11 January 2026
Method 1: Using For Loop
Iterative approach.
Main.javaRun in Compiler →
public class Factorial {
public static void main(String[] args) {
int num = 5;
long factorial = 1;
for(int i = 1; i <= num; ++i) {
factorial *= i;
}
System.out.printf("Factorial of %d = %d", num, factorial);
}
}Output:
Factorial of 5 = 120
Explanation
We multiply numbers from 1 to n. 1 * 2 * 3 * 4 * 5 = 120.
Method 2: Using Recursion
Recursive approach.
Main.javaRun in Compiler →
public class Factorial {
public static void main(String[] args) {
int num = 5;
long factorial = multiplyNumbers(num);
System.out.println("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num) {
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}Output:
Factorial of 5 = 120
Explanation
Function calls itself: 5 * fact(4) -> 5 * 4 * fact(3) ...
Frequently Asked Questions
Try This Program
Copy this code and run it in our free online Java compiler.
Open Java Compiler