Bird
0
0

Identify the problem in this code:

medium📝 Debug Q7 of 15
Java - Classes and Objects

Identify the problem in this code:

class Printer {
  void print(String message) { System.out.println(message); }
}
public class Test {
  public static void main(String[] args) {
    Printer p = null;
    p.print("Hello");
  }
}
ACannot print strings in Java
BSyntax error in print method
CNullPointerException because p is null
DMissing return type in main method
Step-by-Step Solution
Solution:
  1. Step 1: Check object reference

    p is assigned null, so calling p.print() causes NullPointerException at runtime.
  2. Step 2: Verify other options

    print method syntax is correct, main method has return type void, printing strings is valid.
  3. Final Answer:

    NullPointerException because p is null -> Option C
  4. Quick Check:

    Calling method on null object causes exception [OK]
Quick Trick: Never call methods on null objects [OK]
Common Mistakes:
  • Confusing syntax errors with runtime exceptions
  • Thinking main needs return type int
  • Believing Java cannot print strings

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes