In this Java program, we will learn how to find the factorial of a number using a simple for loop. We will also see a Java 8 version using a lambda expression.
What is Factorial?
The factorial of a positive integer n is the product of all positive integers from 1 to n.
For example:
5! = 5 × 4 × 3 × 2 × 1
5! = 120
1. Normal Java Program
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial = factorial * i;
}
System.out.println("Factorial of " + number + " = " + factorial);
sc.close();
}
}
Output
Enter a number: 5
Factorial of 5 = 120
Explanation
The program first accepts a number from the user.
int number = sc.nextInt();
The factorial variable is initialized with 1:
long factorial = 1;
A for loop is then used to multiply all numbers from 1 to the given number:
for (int i = 1; i <= number; i++) {
factorial = factorial * i;
}
For example, when the input is 5:
1 × 2 × 3 × 4 × 5 = 120
2. Java 8 Program to Find Factorial
Java 8 introduced lambda expressions and functional interfaces. We can use them to create a simple factorial function.
import java.util.Scanner;
import java.util.function.Function;
public class FactorialJava8 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = sc.nextInt();
Function<Integer, Long> factorial =
n -> {
long result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
};
System.out.println("Factorial of " + number + " = "
+ factorial.apply(number));
sc.close();
}
}
Output
Enter a number: 6
Factorial of 6 = 720
Explanation of Java 8 Program
The Java 8 program uses the Function functional interface:
Function<Integer, Long>
The lambda expression defines the factorial calculation:
n -> {
long result = 1;
for (int i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
The factorial function is executed using:
factorial.apply(number)
Difference Between Normal Java and Java 8
| Feature | Normal Java | Java 8 |
|---|---|---|
| Approach | for loop | Lambda + Function |
| Loop | Yes | Yes |
| Lambda expression | No | Yes |
| Functional interface | No | Yes |
| Beginner friendly | Very easy | Moderate |
| Java Version | All common versions | Java 8+ |
Important Note
For a simple factorial problem, the normal for loop is recommended. Java 8 does not mean every program needs Streams or Lambda expressions. The Java 8 version is mainly useful for learning functional programming features.
Conclusion
The factorial of a number can be calculated easily using a for loop. The traditional Java approach is simple and beginner-friendly, while the Java 8 approach demonstrates how lambda expressions and functional interfaces can be used in Java.