how to destroy an object in java?

nr5 picture nr5 · Nov 3, 2012 · Viewed 158.1k times · Source

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.
  1. The answer should be e?

  2. 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 ?

Answer

kosa picture kosa · Nov 3, 2012

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.