Return to site

☕🎓JAVA CERTIFICATION QUESTION: garbage-collected when no longer referenced

· java,ocp

Given the following:



When will the Car instance created at line n1 become eligible for garbage collection? Choose one.

* After line n2

* After line n3

* After line n4

* After line n5

* After the code throws an exception and leaves the method containing this fragment

Answer: After line n3

First, the code instantiates an ArrayList and stores a reference to it in the variable l, which is of type List.

Because both the Car and Engine classes are serializable, the list will accept both these types if you try to add them.

Next, the code creates a Car object. Soon the code will add it to the list at position zero.

However, look at the construction of the Car.

At a quick glance, you might assume that the construction uses the following constructor:


Look closer: This is not a constructor. It’s a method with an egregiously poor name!

It’s likely that it was intended to be a constructor, but somebody’s fingers typed void.

In view of the above, you now know that the constructor that initializes the Car is actually the default constructor.

Importantly, this will do nothing to initialize the field Engine e, so it remains at the default value of null.

After the construction of the Car, the code calls c.getEngine(). This call returns null, and that’s stored in the variable e.

The next two steps call add(0, _).

This two-argument version of add stores values at the given index, moving items to the higher index positions as needed to make space.

In this case, the items are added to the very front of the list.

At this point, you have a null in position zero and a Car in position one.

The Car started at position zero but was pushed down to make space for the null.

Line n2 overwrites the variable c with null. At this point, the only reference left to the Car object is at index one of the list.

Because a reference remains, the object is not yet eligible for garbage collection.

Line n3 overwrites the reference stored at index one of the list.

Immediately after this set operation, there are no references left to the Car object.

That makes it eligible for garbage collection.

To recap, no exceptions are thrown, and the Car object is eligible for garbage collection after line n3.