Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q13 of 15
Java - Object-Oriented Programming Concepts
What will be the output of the following code?
class Dog {
  String name;
  void bark() {
    System.out.println(name + " says Woof!");
  }
}

public class Main {
  public static void main(String[] args) {
    Dog dog1 = new Dog();
    dog1.name = "Buddy";
    dog1.bark();
  }
}
Anull says Woof!
BWoof!
CCompilation error
DBuddy says Woof!
Step-by-Step Solution
Solution:
  1. Step 1: Understand object property assignment

    The object dog1 has its name set to "Buddy" before calling bark().
  2. Step 2: Analyze the bark method output

    The method prints the name followed by " says Woof!" so it prints "Buddy says Woof!".
  3. Final Answer:

    Buddy says Woof! -> Option D
  4. Quick Check:

    Object property used in method = Buddy says Woof! [OK]
Quick Trick: Check object fields before method calls for output [OK]
Common Mistakes:
  • Assuming default null value prints
  • Forgetting to assign the name
  • Thinking method prints only 'Woof!'

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes