Last Updated : 30 Jul, 2025
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.
Just before destroying any object, the garbage collector always calls the finalize() method to perform clean-up activities on that object. This process is known as Finalization in Java. The Garbage collector calls the finalize() method only once on any object.
Syntax of finalize()Note: The finalize() method has been deprecated since Java 9 and removed in Java 18 (JEP 421).
It is not recommended for use in modern Java applications. Prefer alternatives like try-with-resources, AutoCloseable or java.lang.ref.Cleaner for resource management and cleanup.
protected void finalize() throws Throwable
Since the Object class contains the finalize method, hence finalize method is available for every Java class since Object is the superclass of all Java classes. Since it is available for every Java class, the Garbage Collector can call the finalize() method on any Java object.
How to Override finalize() MethodThe 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.
Example: Overriding finalize() Method
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();
}
}
Inside Geeks's finalize() Calling finalize() of Object class
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4