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;
  void setName(String n) {
    name = n;
  }
  void printName() {
    System.out.println(name);
  }
}
public class Test {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.setName("Buddy");
    d.printName();
  }
}
ABuddy
Bnull
CCompilation error
DRuntime error
Step-by-Step Solution
Solution:
  1. Step 1: Trace method calls

    Object d calls setName("Buddy"), setting name to "Buddy".
  2. Step 2: Print the name

    printName() prints the value of name, which is "Buddy".
  3. Final Answer:

    Buddy -> Option A
  4. Quick Check:

    Instance method sets and prints value correctly [OK]
Quick Trick: Instance methods can change and access object data [OK]
Common Mistakes:
  • Expecting null because of uninitialized variable
  • Confusing static and instance context
  • Assuming compilation or runtime errors

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes