Interview Q&A · Java · 4 questions in this topic
Objects, References and Garbage Collection — Java Interview Q&A
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
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.
Are objects passed to methods in Java?
Answer
No. Java is strictly pass-by-value for every argument, including objects. When you pass an object, the value that is copied is the reference to it, so the method can mutate the shared object but cannot change which object the caller variable points to. Reassigning the parameter inside the method has no effect on the caller.
Example
void rename(Employee e) { e.setName("Ada"); // visible to caller: same object mutated e = new Employee(); // not visible: only the copied reference is repointed }
💡 Say the exact phrase: Java passes the reference by value.
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission