The finalize() method was originally designed to allow an object to perform cleanup operations before being removed from memory by the Garbage Collector. However, it is deprecated and should not be used in modern Java applications because its execution is unpredictable and can negatively impact performance.
Key Points: • The finalize() method belongs to the Object class. • It may be invoked by the Garbage Collector before reclaiming an object's memory. • There is no guarantee that finalize() will be executed before the object is destroyed. • Due to reliability and performance issues, finalize() was deprecated starting from Java 9. • Modern Java applications use try-with-resources or explicit resource management instead of finalize().
Example: Suppose an object holds a file or network resource. Earlier, developers could override finalize() to release those resources, but today try-with-resources is the recommended approach.
Code Example:
class Demo {
@Override
protected void finalize() throws Throwable {
System.out.println("Cleanup performed");
}
}Interview Tip: A concise interview answer is:
"The finalize() method was intended to perform cleanup before an object is garbage collected. However, it is deprecated because its execution is not guaranteed. Modern Java applications use try-with-resources and explicit resource management instead of finalize()."