< Prev
Next >



Java finalize() method





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 a 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() 





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 the garbage collector.





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

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


Output -


Object is garbage collected
Object is garbage collected


Program Analysis





Note :




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
-
Python

Ad2