Bird
0
0

What will be the output of the following Java code?

medium📝 Predict Output Q13 of 15
Java - Inheritance
What will be the output of the following Java code?
class Test {
  Test() {
    this(5);
    System.out.print("A");
  }
  Test(int x) {
    System.out.print("B");
  }
  public static void main(String[] args) {
    new Test();
  }
}
AAB
BBA
CA
DB
Step-by-Step Solution
Solution:
  1. Step 1: Trace constructor calls

    Creating new Test() calls the no-arg constructor, which calls Test(int x) first (prints "B"), then prints "A".
  2. Step 2: Determine output order

    Since Test(int x) prints "B" first, then control returns to no-arg constructor which prints "A", output is "BA".
  3. Final Answer:

    BA -> Option B
  4. Quick Check:

    Constructor chaining prints B then A [OK]
Quick Trick: Constructor chaining prints inner constructor output first [OK]
Common Mistakes:
  • Assuming outer constructor prints before inner
  • Confusing order of constructor calls
  • Ignoring that this() must be first line

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes