Bird
0
0

Find the problem in this code:

medium📝 Debug Q7 of 15
Java - Memory Management Basics
Find the problem in this code:
String s1 = "Java";
String s2;
s2 = s1;
s1 = null;
System.out.println(s2.length());
ACompilation error due to uninitialized s2
BPrints 4 without error
CNullPointerException at runtime
Ds2 becomes null after s1 is null
Step-by-Step Solution
Solution:
  1. Step 1: Assign references

    s2 is assigned to point to the same String object as s1 ("Java").
  2. Step 2: Nullify s1 and print s2 length

    Setting s1 to null does not affect s2, which still points to "Java". Calling length() on s2 returns 4.
  3. Final Answer:

    Prints 4 without error -> Option B
  4. Quick Check:

    Nullifying one reference doesn't affect others [OK]
Quick Trick: Null one reference, others still valid if pointing same object [OK]
Common Mistakes:
  • Assuming s2 becomes null when s1 is null
  • Expecting NullPointerException incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes