Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q5 of 15
Java - Inheritance
What will be the output of this code?
class Sample {
  Sample() {
    this(5);
    System.out.println("Default");
  }
  Sample(int x) {
    this("Hello");
    System.out.println("Int: " + x);
  }
  Sample(String s) {
    System.out.println("String: " + s);
  }
  public static void main(String[] args) {
    new Sample();
  }
}
AString: Hello Default Int: 5
BDefault Int: 5 String: Hello
CString: Hello Int: 5 Default
DInt: 5 String: Hello Default
Step-by-Step Solution
Solution:
  1. Step 1: Follow constructor chaining order

    The no-arg constructor calls this(5), which calls the int constructor.
  2. Step 2: Continue chaining inside int constructor

    The int constructor calls this("Hello"), which prints "String: Hello" first.
  3. Step 3: Print statements after chaining

    After the string constructor finishes, int constructor prints "Int: 5", then no-arg constructor prints "Default".
  4. Final Answer:

    String: Hello Int: 5 Default -> Option C
  5. Quick Check:

    Chaining nests calls in order [OK]
Quick Trick: Nested this() calls run deepest constructor first [OK]
Common Mistakes:
  • Ignoring nested chaining order
  • Mixing print order
  • Assuming constructors run independently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes