Today, we will explore how to write a factorial Java program. Java is one of the most widely used programming languages, and learning Java programs to tackle common life problems is a major step in becoming a Java developer.
One such important problem to learn is- calculating the factorial Java program, It is among the popular questions often asked in technical or coding interviews. So today, We’ll learn how to implement factorials in Java using various methods.
What Is A Factorial?
Before moving to the factorial Java program, it is important to make a solid foundational base. So, let us begin by understanding the concept of factorial first. Factorial is basically a mathematical function that multiplies a given positive integer by all the positive integers less than it. For example, the factorial of 5 written as “5!” is calculated as –
5*4*3*2*1 = 120. |
Let us understand it in more simpler terms, you keep multiplying the number by each smaller number until you reach 1. Factorials are often used in mathematical computations involving permutations and combinations.
Methods To Write Factorial Java Program
When writing a factorial Java program, there are various methods available, each with its own unique approach. These methods include using loops, recursion, and even more advanced techniques like memoization. Each method has its own advantages and is suited to different situations depending on the problem’s requirement. Let’s explore these methods in detail:
1. Factorial Java Program Using For Loop
The very first and simple step in the factorial Java program is to print a factorial program using a for loop. Let us understand this with the help of the code below and understand the step-by-step explanation of this.
Factorial Java Program Using For Loop |
public class Factorial {
public static void main(String[] args) { int number = 8; //Number for which we have to find factorial. long factorial = 1; for (int i = 1; i <= number; i++) { factorial *= i; } System.out.println(“Factorial of a number ” + number + ” = ” + factorial); } } |
Output-
Factorial of 8 = 40,320 |
Step-By-Step Explanation Of For Loop
- Define the number: Start by declaring the number for which you want to calculate the factorial in the main function.
- Initialize result: Create a variable `result` and set it to 1. This will store the factorial as it is calculated.
- Set up the loop: Use a for loop that starts from 1 and increments up to the given number.
- Multiply in the loop: Within the loop, multiply `result` by the current loop index (`i`).
- Return the result: After the loop ends, `result` will hold the factorial value.
Factorial Java Program Using While Loop
In Java programming, the while loop is a powerful tool, which is generally used when we don’t know in advance how many times a task needs to be repeated. When writing a factorial Java program, the while loop allows us to iteratively multiply numbers starting from 1 up to the given number, this method is perfect for scenarios where the exact number of iterations varies based on user input.
Factorial Java Program Using While Loop |
import java.util.Scanner;
public class FactorialWhileLoop { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter number for factorial: “); int number = scanner.nextInt(); long factorial = 1; // Using long to handle large factorials int i = 1; while (i <= number) { factorial *= i; i++; } System.out.println(“The factorial of” + number + ” = ” + factorial); } } |
Output-
Enter number for factorial: 8 The factorial of 8 = 40,320 |
Factorial Java Program Using Recursion
Recursion in Java programming involves a method calling itself to solve problems. In this approach, the factorial of a number is computed by breaking down the problem into smaller, simpler subproblems until a base case is reached. For factorial, the base case is when the number is 0 or 1, where the factorial is defined as 1. It is suitable for scenarios where breaking down a problem into smaller tasks is beneficial.
Factorial Java Program Using Recursion |
import java.util.Scanner;
public class FactorialRecursion { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number: “); int number = scanner.nextInt(); long factorial = factorial(number); System.out.println(“Factorial of ” + number + ” = ” + factorial); } public static long factorial(int n) { if (n == 0) { return 1; // Base case for the given function } else { return n * factorial(n – 1); // Recursive calling } } } |
Output- |
Step-By-Step Explanation Of Recursion Program
- Import scanner class- The first step is to import the scanner class, which is mainly responsible for reading the user input.
- Declare Variable- Declare a variable that will be storing the factorial of the number.
- Prompt user to ask number- Now, ask the user to enter the number for which they want to find factorial.
- Take the number as a parameter- take the number entered by the user as the fixed parameter.
- Create a base condition- Create the base condition in the program that says- “whenever the value goes to 0, we will return 1.
- Now, the last step is to keep calling the function repeatedly until the base condition is met.
Factorial Java Program Using Ternary Operator
In Java, the ternary operator lets you choose between two values based on a condition. It’s a shortcut for simple decisions in code, like saying “if this is true, use this value; otherwise, use that value”. This makes code shorter and easier to follow for basic choices.
Factorial Java Program Using Ternary Operator |
import java.util.Scanner;
public class FactorialUsingTernaryOperator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter a number to calculate factorial: “); int number = scanner.nextInt(); long factorial = (number == 0 || number == 1) ? 1 : calculateFactorial(number); System.out.println(“Factorial of ” + number + ” is: ” + factorial); scanner.close(); } public static long calculateFactorial(int n) { return (n == 1) ? 1 : n * calculateFactorial(n – 1); } } |
Output- |
Step-By-Step Explanation
- Define the number: Start by specifying the number for which you want to calculate the factorial in the main function.
- Set up storage: Use a data structure (like a HashMap) to store previously calculated factorial values.
- Check stored values: In the recursive function, check if the result for the current number is already stored. If it is, return it.
- Recursive call: If the result is not stored, calculate it by multiplying the number by the factorial of the number minus 1, and store this result.
- Return the result: This process avoids redundant calculations by storing and reusing results.
Learn Factorial Java Program With PW Skills
Start your journey of learning Java programming with our exclusive PW Skills Java With DSA Course.
The key features of this course that make it a standout choice among students include- Mentorship from expert industrialists, regular doubt-clearing sessions, daily practice sheets, in-demand course curriculum, placement assistance, PW alumni support, and much more. So, don’t waste much of your time, Visit pwskills.com today and start your journey of becoming a skilled Java Developer with us.
Factorial Java Program FAQs
While writing a factorial program in Java, Which approach is better: recursion or iteration?
Both approaches have their own unique features and benefits, but iteration is generally preferred for factorial calculations due to better performance and avoidance of stack overflow issues in case of large values of numbers. Recursion is simpler and more elegant but can be inefficient for large inputs.
What is stack overflow in the context of recursion?
Stack overflow occurs when there is excessive use of the call value due to deep or infinite recursion. This can happen in a recursive factorial program if the input number is very large.
What are common mistakes in writing a factorial program?
Common mistakes include not handling the base case correctly in recursion, causing stack overflow with large inputs, and not considering the limitations of data types for large factorials apart from all these writing the syntax and code correctly is also one of the major concern.