+1 vote
in JAVA by
What is the purpose of the finalize() method?

1 Answer

0 votes
by
The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects). The cleanup processing is the process to free up all the resources, network which was previously used and no longer needed. It is essential to remember that it is not a reserved keyword, finalize method is present in the object class hence it is available in every class as object class is the superclass of every class in java. Here, we must note that neither finalization nor garbage collection is guaranteed. Consider the following example.

public class FinalizeTest {  

    int j=12;  

    void add()  

    {  

        j=j+12;  

        System.out.println("J="+j);  

    }  

    public void finalize()  

    {  

        System.out.println("Object is garbage collected");  

    }  

    public static void main(String[] args) {  

        new FinalizeTest().add();  

        System.gc();  

        new FinalizeTest().add();  

    }  

}

Related questions

+1 vote
asked May 12, 2021 in JAVA by rajeshsharma
+1 vote
asked May 5, 2021 in JAVA by SakshiSharma
...