Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

The finalize() method

Sometimes an object will need to complete some important task before it gets destroyed such as closing an open connection, etc. If these connections are not closed, then it will create problem in some applications (e.g., web application).

Garbage collector does not perform such activities of making the resources free held by objects. Therefore it is a responsibility of the programmer to make these resources free just before destroying the object. For that, the programmer can define a very important method called finalize() method in which all the important tasks that object will need to perform before it gets destroyed are done.

Garbage collector calls this finalize() method automatically every time just before destroying the object. Thus all the resources held by object become free before the object gets destroyed and the application runs smoothly.

Syntax of finalize() method

 protected void finalize()
{
    // statements
}

Example

public class Car 
{
    protected void finalize()
    {
        System.out.println("Finalize method called");
        System.out.println("Objects got destroyed");
    }
	
    public static void main(String args[]) 
    {
        Car c1 = new Car();		
        Car c2 = new Car();
        c1 = null;
        c2 = null;
        System.gc();
    }
}

Output

Finalize method called
Objects got destroyed

                                                                             OR

Finalize method called
Objects got destroyed
Finalize method called
Objects got destroyed

                                                                             OR

Something else.

Note

For above program, the output may be different every time we run the program because we can’t predict whether garbage collector will be invoked or not by JVM.
If invoked, we cannot predict for how many times it will be invoked.

 

Leave a reply