Bird
0
0

Identify the problem in this code snippet:

medium📝 Debug Q7 of 15
Java - Classes and Objects
Identify the problem in this code snippet:
class Book {
  String title;
  void setTitle(String title) {
    title = title;
  }
  void printTitle() {
    System.out.println(title);
  }
}
AprintTitle method should be static
BMissing return type in setTitle method
Ctitle variable is declared twice
DThe setTitle method does not update the instance variable
Step-by-Step Solution
Solution:
  1. Step 1: Analyze setTitle method

    Parameter title shadows instance variable title. Assignment title = title; assigns parameter to itself.
  2. Step 2: Effect on instance variable

    Instance variable remains unchanged, so printTitle() prints null.
  3. Final Answer:

    The setTitle method does not update the instance variable -> Option D
  4. Quick Check:

    Use this.title = title; to fix [OK]
Quick Trick: Use 'this' to refer to instance variables when shadowed [OK]
Common Mistakes:
  • Not using 'this' keyword when parameter name matches instance variable
  • Assuming assignment updates instance variable
  • Thinking method lacks return type

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes