Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to destroy an object in java?

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 ?

like image 484
nr5 Avatar asked Nov 03 '12 03:11

nr5


People also ask

How do you remove an object in Java?

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.

How do you make an object destroy itself in Java?

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.

Which function is used to destroy objects Java?

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.

Which function is used to destroy object?

Just as constructor functions create objects, destructor functions destroy objects.


1 Answers

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.

like image 126
kosa Avatar answered Sep 19 '22 17:09

kosa