Finalize() Method in Java

Finalize() Method in Java

Finalize() is a method of Object class which is at the top of java class hierarchy. Garbage Collection is a process of removing objects from memory that are no longer needed. This Garbage collection is performed by Garbage collector. But before destroying these objects the Garbage Collector call the finalize() method to perform clean-up operations. Garbage collector destroys the object as soon as the finalize() method completes.

Cleanup operation includes deallocating the resources like network connection and database connection associated with the object.

This method can raises Throwable exception.


protected void finalize() throws Throwable
    // code to close resources

Since object is a superclass of all Java classes, the Garbage collector can call finalize() method on any Java object.


public class finalize_method {  
     public static void main(String[] args)   
        finalize_method obj = new finalize_method();   
        // printing hash code representation of object created
        // making the object null, if you look at our program this object is not required anywhere
        // anymore after this statement -- System.out.println(obj.hashCode());
        // so if we call garbage collector it will destory this object
        obj = null;   
        // Call to Garbage collector
        // now before destroying obj
        // garbage collector calls finalize on obj like this internally -- obj.finalize()
        // so even if we did not explicitly called finalize() method in the program
        // the contents of the finalize() method are displyed in the ouptput
        // look carefully
        System.out.println("End of garbage collection");   

    protected void finalize()   
        System.out.println("finalize method called");   


End of garbage collection 
finalize method called
If you feel this tutorial is missing something, please fell free to comment down below. Your will be cited for that.