I encountered this question in an interview with following options:
How to destroy an object in java?
a. System.gc(); b. Runtime.getRuntime.gc(); c. object.delete(); d. object.finalize(); e. Java performs gc by itself, no need to do it manually.
The answer should be e?
what if e was not there? then ? clearly c is not the answer. a and b will do gc for the whole application(question requires for one object). I think it is d because finalize() is called just prior to gc(but is it necessary that after finalize gc is invoked ?) or I am wrong ? e must be there to answer this question ?
The remove(Object obj) method of List interface in Java is used to remove the first occurrence of the specified element obj from this List if it is present in the List. Parameters: It accepts a single parameter obj of List type which represents the element to be removed from the given List.
Since an object cannot determine how many references there are to itself, an object cannot "destroy itself". Show activity on this post. The object doesn't have access to the references to it so there's no way to set them to null or something else.
Finalization. Just before destroying an object, Garbage Collector calls finalize() method on the object to perform cleanup activities. Once finalize() method completes, Garbage Collector destroys that object.
Just as constructor functions create objects, destructor functions destroy objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With