finalize() method in Java with examples

In this tutorial, we are going to learn about the finalize method in Java with some examples.

finalize() method

Finalize is a method of an object class in which the garbage collector is called before destroying the object.

This method does not have any return type, it performs clean up activities.

The finalize method overrides to dispose of system resources,  is also useful to minimize memory leak.

First Example

The code given below will explain the use of finalize method in Java.

When we take a string object and make it null then it will not call the finalize method.

public class finalizeMethod {
     public static void main(String[] args)
    {

 	String str1 = new String("CS");
        str1 = null;

       
        System.gc();
        System.out.println("output of main method");

    }
    
    protected void finalize()
    {
        System.out.println("output of finalize method");
    }
}
Output:-
output of main method

EXAMPLE 2

But when we take the object of the class and make it null then, first it will call the main method after that it will call the finalize method.

public class finalizeMethod {
     public static void main(String[] args)
    {


  finalizeMethod str2 = new finalizeMethod ();
  str2 = null;
       
        System.gc();
        System.out.println("output of main method");

    }
    
    protected void finalize()
    {
        System.out.println("output of finalize method");
    }
}

Output:-

output of main method
output of finalize method

Also read: toString() method in Java

Leave a Reply

Your email address will not be published. Required fields are marked *