Skip to content
Advertisement

Java object garbage collection

I am working on the OCA Java certification and unsure of how to understand the answer to one question.

JavaScript

The question is which object will be available for garbage collection after the //HERE point.

The answer provided by the online test is : One object (o1).

Can someone explain me why?

Advertisement

Answer

Consider a simple class Student.

Step 1 :

JavaScript

s1, s2, s3 are referencing 3 object in the heap space

enter image description here

Step 2 :

JavaScript

s1 is now referencing the s3 object in the heap space

the object s1 in the heap space has lost his reference

enter image description here

Step 3 :

JavaScript

Variable s1 reference s3 heap space

Variable s3 reference s2 heap space

enter image description here

Step 4 :

JavaScript

Variable s1 reference s3 heap space

Variable s3 reference s2 heap space

Variable s2 lost his reference (null pointer)

enter image description here

Conclusion :

After line 11, one object is eligible for garbage collection

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement