Bird
0
0

Identify the error in the following Java code related to object lifecycle:

medium📝 Debug Q7 of 15
Java - Classes and Objects
Identify the error in the following Java code related to object lifecycle:
class Example {
    Example() {
        System.out.println("Example created");
    }
    public static void main(String[] args) {
        Example e = new Example();
        e = null;
        System.out.println(e.hashCode());
    }
}
ACompilation error due to null assignment
BNullPointerException at runtime
CNo error, prints hash code
DConstructor is not called
Step-by-Step Solution
Solution:
  1. Step 1: Object Creation

    The constructor prints "Example created" when new Example() is called.
  2. Step 2: Null Assignment

    The reference e is set to null, so it no longer points to the object.
  3. Step 3: Method Call on Null

    Calling e.hashCode() on a null reference causes a NullPointerException at runtime.
  4. Final Answer:

    NullPointerException at runtime -> Option B
  5. Quick Check:

    Calling method on null reference throws exception [OK]
Quick Trick: Calling methods on null references causes exceptions [OK]
Common Mistakes:
  • Thinking null assignment causes compile error
  • Assuming method call on null prints hash code
  • Ignoring runtime exceptions from null dereference

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes