Bird
0
0

Find the error in this Java code snippet involving object interaction:

medium📝 Debug Q14 of 15
Java - Classes and Objects

Find the error in this Java code snippet involving object interaction:

class Printer {
    void print(String message) {
        System.out.println(message);
    }
}

public class Main {
    public static void main(String[] args) {
        Printer printer;
        printer.print("Hello World");
    }
}
AThe print statement syntax is incorrect.
BThe method 'print' is not defined in the Printer class.
CThe object 'printer' is declared but not initialized before use.
DThe class Printer should be public.
Step-by-Step Solution
Solution:
  1. Step 1: Check object declaration and initialization

    The object 'printer' is declared but never assigned a new Printer instance.
  2. Step 2: Understand consequences of uninitialized object

    Calling a method on an uninitialized object causes a NullPointerException at runtime.
  3. Final Answer:

    The object 'printer' is declared but not initialized before use. -> Option C
  4. Quick Check:

    Uninitialized object causes runtime error [OK]
Quick Trick: Always initialize objects before calling methods [OK]
Common Mistakes:
  • Assuming declaration equals initialization
  • Thinking method absence causes error here
  • Ignoring runtime NullPointerException

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes