Bird
0
0

What is the output of this Java program?

medium📝 Predict Output Q5 of 15
Java - Methods and Code Reusability
What is the output of this Java program?
public class FactorialTest {
  public static void main(String[] args) {
    System.out.println(fact(4));
  }
  static int fact(int n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);
  }
}
A10
B24
C4
D1
Step-by-Step Solution
Solution:
  1. Step 1: Understand recursion

    fact(4) calls fact(3), fact(2), fact(1).
  2. Step 2: Calculate factorial

    fact(1) returns 1, fact(2) returns 2*1=2, fact(3) returns 3*2=6, fact(4) returns 4*6=24.
  3. Final Answer:

    24 -> Option B
  4. Quick Check:

    Factorial of 4 is 24 [OK]
Quick Trick: Factorial multiplies down to 1 recursively [OK]
Common Mistakes:
  • Stopping recursion too early
  • Adding instead of multiplying
  • Misunderstanding base case

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes