finalize() Method in Java and How to Override it?

Last Updated : 30 Jun, 2026

The finalize() method in Java is called by the Garbage Collector just before an object is destroyed. It allows the object to perform a clean-up activity. Clean-up activity means closing the resources associated with that object, like Database Connection, Network Connection or we can say resource de-allocation.

  • It is defined in the Object class and available to all Java classes.
  • It is not a reserved keyword.
  • Can be overridden to perform cleanup activities.
Java
class Student {

    @Override
    protected void finalize() throws Throwable {
        System.out.println("Cleanup before object is destroyed.");
    }

    public static void main(String[] args) {

        Student s = new Student();

        try {
            s.finalize();   // Only for demonstration
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

Output
Cleanup before object is destroyed.

Explanation: In this example, the Student class overrides the finalize() method to print a cleanup message. The method is called manually only for demonstration purposes. In normal execution, finalize() is invoked by the Garbage Collector, but because its execution is unpredictable and the method is deprecated, modern Java programs should use resource management techniques such as try-with-resources instead.

Syntax

@Override
protected void finalize() throws Throwable {
// Cleanup code
}

Override finalize() Method 

The finalize method, which is present in the Object class, has an empty implementation. In our class, clean-up activities are there. Then we have to override this method to define our clean-up activities. In order to override this method, we have to define and call finalize within our code explicitly.

Java
import java.lang.*;


public class Geeks {

    // Overriding finalize() to perform cleanup
    @Override
    protected void finalize() throws Throwable {
        try {
            System.out.println("Inside Geeks's finalize()");
        } catch (Throwable e) {
            throw e;
        } finally {
            System.out.println("Calling finalize() of Object class");
            
            // call to Object class finalize()
            super.finalize(); 
        }
    }

    public static void main(String[] args) throws Throwable {
        
        // Creating object
        Geeks g = new Geeks();

        // Manually calling finalize 
        g.finalize();
    }
}

Output
Inside Geeks's finalize()
Calling finalize() of Object class

Explanation: In this example, the finalize() method is overridden to perform cleanup before the object is destroyed. The method prints a message, then calls super.finalize() to execute the Object class cleanup. Here, finalize() is called manually only for demonstration purposes; in real applications, it is normally invoked by the Garbage Collector (though it is deprecated and should not be relied upon).

Comment