Bird
0
0

Consider this code:

medium📝 Predict Output Q5 of 15
Java - Memory Management Basics
Consider this code:
class Sample {
  public static void main(String[] args) {
    Sample s1 = new Sample();
    Sample s2 = new Sample();
    s1 = s2;
    s2 = null;
    System.out.println(s1 == null);
  }
}
What is the output?
Atrue
BCompilation error
CNullPointerException
Dfalse
Step-by-Step Solution
Solution:
  1. Step 1: Follow reference assignments

    s1 and s2 start as different objects. Then s1 points to s2's object, and s2 is set to null.
  2. Step 2: Check s1's null status

    s1 still points to the second object, so s1 == null is false.
  3. Final Answer:

    false -> Option D
  4. Quick Check:

    Reference reassignment keeps s1 non-null [OK]
Quick Trick: Reference reassignment keeps object alive if still referenced [OK]
Common Mistakes:
  • Thinking s1 becomes null when s2 is null
  • Confusing object references with object deletion
  • Expecting runtime exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes