Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
Java - Constructors

What will be the output of the following code?

class Animal {
Animal() { System.out.println("Animal created"); }
Animal(String name) { System.out.println("Animal named " + name); }
}
public class Test {
public static void main(String[] args) {
Animal a1 = new Animal();
Animal a2 = new Animal("Tiger");
}
}
AAnimal named Tiger Animal created
BAnimal created Animal named Tiger
CAnimal created Animal created
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Analyze constructor calls

    a1 calls Animal() constructor which prints "Animal created".
    a2 calls Animal(String) constructor which prints "Animal named Tiger".
  2. Step 2: Determine output order

    First line prints from a1 creation.
    Second line prints from a2 creation.
  3. Final Answer:

    Animal created Animal named Tiger -> Option B
  4. Quick Check:

    Constructor called depends on arguments passed. [OK]
Quick Trick: Constructor called matches argument list. [OK]
Common Mistakes:
  • Assuming constructors print in reverse order.
  • Confusing constructor overloading with method overriding.
  • Expecting compilation error due to multiple constructors.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes