Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Classes and Objects
What will be the output of this code?
class Dog {
  String name = "Buddy";
}

public class Test {
  public static void main(String[] args) {
    Dog d1 = new Dog();
    Dog d2 = new Dog();
    d2.name = "Max";
    System.out.println(d1.name + ", " + d2.name);
  }
}
ABuddy, Max
BMax, Max
CBuddy, Buddy
DCompilation error
Step-by-Step Solution
Solution:
  1. Step 1: Understand instance variable values per object

    d1 and d2 are separate objects, each with its own 'name'. d1.name is "Buddy" and d2.name is changed to "Max".
  2. Step 2: Print values of both objects

    Printing d1.name and d2.name outputs "Buddy, Max".
  3. Final Answer:

    Buddy, Max -> Option A
  4. Quick Check:

    Instance variables differ per object = Buddy, Max [OK]
Quick Trick: Each object has its own instance variable copy. [OK]
Common Mistakes:
  • Assuming instance variables are shared across objects.
  • Expecting both names to be "Max".
  • Thinking code causes compilation error.

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes