A method named finalize() is executed before an object is de-allocated from the heap memory by the garbage collector. Each class inherits
the finalize() method from the Object class, which is the superclass of all java classes. We can override the finalize() method to give it our own preferred definition.
Signature of finalize() method
public void finalize()
This finalize() method has-
A public access.
It doesn't return any value, hence, a void return type.
It does not accept any parameters.
Note :
The finalize() method runs only once in the lifetime of an object, i.e. just before an object
is about to be de-allocated from the heap memory by the garbage collector.
Advertisement
Example of finalize() method
//Java - Example of finalize() method
class A
{
//overriding finalize() method inherited from Object class.
public void finalize()
{
System.out.println("Object is garbage collected");
}
public static void main(String... ar)
{
Runtime run = Runtime.getRuntime();
A ob;
//Creating 10 objects of class A
for(int i=0; i<10;i++)
{
ob = new A();
}
//Making a request to garbage collector to de-allocate the unreferenced objects.
run.gc();
}
}
Output -
Object is garbage collected
Object is garbage collected
Program Analysis
As you may see in the last code, we have created 10 objects of class A.
In the last iteration of for-loop, only the last object is referenced by the reference variable ob but the rest of first 9 objects are not referenced by any reference variable and are eligible for garbage collection.
Next, on making a request to garbage collector, the finalize() method is executed only twice, before the de-allocation of an object from the Heap memory.
Note :
The above example shows that only two objects are taken off the heap memory by the garbage collector while the rest 8 objects are still on the Heap memory.
This proves that by calling gc() method, we only make a request to JVM to run the garbage collector
to de-allocate the unreferenced objects but the actual number of object that are deallocated
or whether JVM decides to runs the garbage collector
is only a sole wish of JVM.