Finalize method in Java

Fellow coders, in this tutorial we are going to learn about the finalize() method in Java programming language. We will also work on an example by implementing this method in a java program and then running that program.

Before getting to know about finalize() method in Java, we must know about the process of garbage collection in Java and understand why we need this specific function.

What is Garbage Collection in Java?

Garbage collection in Java is a very simple process that proves to be of much importance in memory management. In the process of garbage collection, the collector looks at the heap memory and identifies which objects are in use and which objects are not in use. An unused object simply means that there is no pointer to that object and its consuming memory. The garbage collector simply removes (deletes) these objects.

What is the Finalize method in Java?

The finalize method is a method in Java programming language that is called just before the deletion of objects by the garbage collector. In this way finalize() method is of much use as we can perform some tasks such as clean-ups, clear out the system resources, etc. We can rest assured that our finalize() method will run just before garbage collection is done. In this way, we can de-allocate all the resources with the help of this method in Java.

Working with the code:

class Letsfinalize{
  public static void main(String[] args){
    
    Letsfinalize mObject = new Letsfinalize();
    mObject = null;

    // calling garbage collector
    System.gc();
    System.out.println("Main method");

  }

  public void finalize(){
    System.out.println('Overriding finalize method');
  }
}

Output

Overriding finalize method
Main method

Leave a Reply

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