Bird
0
0

Consider this Java code snippet:

hard📝 Application Q15 of 15
Java - Memory Management Basics
Consider this Java code snippet:
class Node {
  int value;
  Node next;
  Node(int val) { value = val; }
}

public class Test {
  public static void main(String[] args) {
    Node n1 = new Node(1);
    Node n2 = new Node(2);
    n1.next = n2;
    n2.next = n1;
    n1 = null;
    n2 = null;
    // What happens to the Node objects in heap?
  }
}

What happens to the two Node objects in heap after n1 and n2 are set to null?
ABoth objects become unreachable and eligible for garbage collection.
BObjects remain in heap because they reference each other, preventing garbage collection.
COnly <code>n1</code> object is collected, <code>n2</code> remains.
DObjects cause a memory leak and crash the program.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze object references after null assignments

    Both n1 and n2 references are set to null, so no external references point to these objects.
  2. Step 2: Understand garbage collection with cyclic references

    Even though the two objects reference each other, Java's garbage collector detects unreachable cycles and frees them.
  3. Final Answer:

    Both objects become unreachable and eligible for garbage collection. -> Option A
  4. Quick Check:

    Unreachable objects, even cyclic, are collected [OK]
Quick Trick: Java GC collects unreachable cyclic objects too [OK]
Common Mistakes:
  • Thinking cyclic references prevent garbage collection
  • Assuming memory leak without external references
  • Confusing references with reachability

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes