Interview Q&A · Java · 4 questions in this topic

Objects, References and Garbage Collection — Java Interview Q&A

All Java topics

The difference between objects and the references that point to them, and how garbage collection treats each. Part of Objects, References & Memory · 294 questions in the Java bank.

Object vs reference - what is the difference?

Answer

An object is heap data with state and behaviour, while a reference is a typed handle used to reach that object. Assigning one reference to another or passing one to a method copies only the handle, so both copies still reach the same object. Objects themselves have no names and cannot be copied or passed directly; everything goes through references.

Example

Example.javajava
Employee a = new Employee();
Employee b = a; // copies the reference; one shared object, two handles

What gets garbage collected - objects or references?

Answer

Only objects are garbage collected, and only once they become unreachable. References themselves are ordinary variables stored on the stack or inside other objects, and they simply disappear when their scope ends. Clearing or overwriting the last reference to an object is what makes that object eligible for collection.

How many times does finalize() run, and who calls it?

Answer

The garbage collector finalizer thread calls finalize() at most once per object, just before the memory would be reclaimed. You must never rely on it because collection timing is not guaranteed and finalization delays reclamation. The method has been deprecated since Java 9 and is slated for removal, so modern code uses try-with-resources or java.lang.ref.Cleaner to release resources deterministically.

💡 In interviews, name Cleaner and try-with-resources as the replacements.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits