by Dinesh Thakur

It is quite a tedious job to keep track of all the objects that have been created during the program development. It is tougher to keep track of the objects that are not being used now or their reference have been removed or the objects that have gone out of scope.

An object is eligible for garbage collection when there are no more references to that object. As soon as the variable goes out of scope, the references in the variable are automatically dropped. The references can also be explicitly dropped by setting the variable value to null. In Java, the memory is allocated to the objects using 'new' operator. In languages like C++, the memory is de allocated using 'delete' operator. This process of deallocating memory is called garbage collection. Java deallocates the memory itself. When no reference to an object is found, the object is assumed to be not needed any more. So, the memory allocated to that object can be reclaimed. There is no need to explicitly destroy objects.

 

There may occur a situation when the object, that is being destroyed, need to perform some action. To handle such situations, Java provides 'a mechanism called finalization. So, we simply need to add finalize () method to our class. The general form of finalize () method is:

 

Protected void finalize ()

{

//finalization code

}

 

We need not worry about the use of finalize () in our programs since it is used in very rare cases where the object is not under the control of the garbage collector.