Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training

Hi!

As I was practicing GC exercises, I went through this one.

How many objects are eligible for the garbage collector right after the

execution of the line-11 ?


public class Box {

  private Box n;
  static Box s;

  public static void main(String args[]) {
    Box b1 = new Box();
    b1.n = new Box();
    b1.s = new Box();
    Box b2 = new Box();
    b2.s = b1.n; // line-11
  }
} 


The correct answer is one, and my understanding is that here we have two references inside the Box class - one will be per instance, and another one will be the same among all instances of Box class because of static. And then when we reassign that static reference via b2 instance, all instances now share an updated one, and one object is eligible for GC.

Is my understanding correct?


Thank you!

Correct! The object you free up from the static reference becomes the one eligible for the garbage collection. It would be easier to recognize that if you consider the idea that all references to a static variable from objects of its class has the same meaning as referring that static variable from the class context itself. In other words, b1.s, b2.s, b3.s , ... all are synonyms of B.s


Thank you!

ExamLab © 2008 - 2024