< Prev
Next >



Java finalize() method





A method finalize() is executed before an object is de-allocated from the heap memory by the garbage collector. Each class inherits finalize() method from Object class, which is a superclass of all java classes. We can override finalize() method to give it our own preferred definition.




Signature of finalize() method with its access modifier -


public void finalize() 





Note :


Method finalize() runs only once in the lifetime of an object, i.e. just before an object is about to be de-allocated from heap memory by garbage collector.





finalize() method example


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(); 
}

run.gc(); //Making a request to garbage collector to de-allocate unreferenced objects.
}
}


Output -


Object is garbage collected
Object is garbage collected


Program Analysis



This means only two objects are taken off the heap memory by garbage collection and the rest 8 objects are still on the heap. 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.

Please subscribe our social media channels for notifications, we post a new article everyday.

Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

Coming Next
-
C++ and Python

Ad2