how to destroy an object in java?
To clarify why the other answers can not work:
System.gc()
(along withRuntime.getRuntime().gc()
, which does the exact same thing) hints that you want stuff destroyed. Vaguely. The JVM is free to ignore requests to run a GC cycle, if it doesn't see the need for one. Plus, unless you've nulled out all reachable references to the object, GC won't touch it anyway. So A and B are both disqualified.Runtime.getRuntime.gc()
is bad grammar.getRuntime
is a function, not a variable; you need parentheses after it to call it. So B is double-disqualified.Object
has nodelete
method. So C is disqualified.While
Object
does have afinalize
method, it doesn't destroy anything. Only the garbage collector can actually delete an object. (And in many cases, they technically don't even bother to do that; they just don't copy it when they do the others, so it gets left behind.) Allfinalize
does is give an object a chance to clean up before the JVM discards it. What's more, you should never ever be callingfinalize
directly. (Asfinalize
is protected, the JVM won't let you call it on an arbitrary object anyway.) So D is disqualified.Besides all that,
object.doAnythingAtAllEvenCommitSuicide()
requires that running code have a reference toobject
. That alone makes it "alive" and thus ineligible for garbage collection. So C and D are double-disqualified.
Answer E is correct answer. If E is not there, you will soon run out of memory (or) No correct answer.
Object should be unreachable to be eligible for GC. JVM will do multiple scans and moving objects from one generation to another generation to determine the eligibility of GC and frees the memory when the objects are not reachable.