☕ Java Program – Factorial of a Number | Interview Program
In this video, we learn how to find the Factorial of a Number in Java using loops and conditions.
This is one of the most frequently asked Java interview programs for:
✔ Freshers
✔ College students
✔ Campus placements
You’ll understand:
✅ What is factorial
✅ Positive number factorial
✅ Negative number handling
✅ Why zero is not allowed here
✅ Loop logic
✅ Dry run
🧠 What is Factorial?
Factorial means multiplying all numbers from 1 to N.
Example:
5 factorial = 5 × 4 × 3 × 2 × 1 = 120
Written as:
5! = 120
🧠 Variables Used
num → user input
temp → stores factorial result (starts from 1)
✅ Program Logic Explained
Step 1
Initialize:
temp = 1
Why?
Because factorial uses multiplication.
Step 2 – Check if number is zero
If number is zero:
Should not use zero
(In your program you handled zero separately.)
Step 3 – Positive Number Factorial
If number is positive:
Loop from 1 to num
Inside loop:
temp = temp * i
Each value multiplies with previous result.
Step 4 – Negative Number Factorial
If number is negative:
Loop starts from -1 down to num
Each step:
temp = temp * i
This multiplies negative values.
int temp = 1;
if(num == 0)
{
print "Should not use zero"
}
else if(num is greater than 0)
{
loop i from 1 to num
temp = temp * i
}
else if(num is less than 0)
{
loop i from -1 down to num
temp = temp * i
}
🧪 Dry Run (Positive Example)
num = 5
temp = 1
1 → temp = 1
2 → temp = 2
3 → temp = 6
4 → temp = 24
5 → temp = 120
Final Answer:
👉 120
⭐ Why Interviewers Ask This?
Tests:
✔ Loop concepts
✔ Condition handling
✔ Mathematical logic
✔ Edge cases (zero / negative)
⚠ Common Mistakes
❌ Initializing temp as 0
❌ Wrong loop direction
❌ Forgetting multiplication
❌ Not handling zero
java factorial program
factorial in java
java interview programs
factorial using loop
java logical programs
factorial for negative number
#Java
#FactorialProgram
#JavaInterview
#JavaBasics
#ProgrammingTamil
#Freshers
#LogicalPrograms