Java - finalize() method

What is finalize() method?

finalize() method is called when object is destroyed.

finalize() method can perform resource release or some other type of cleanup, when an object is about to be destroyed.

JVM runs a low priority special task called garbage collector to destroy all objects that are no longer referenced.

Syntax

The Object class has a finalize() method, which is declared as follows:

protected void finalize() throws Throwable { }

The finalize() method in the Object class does not do anything.

The finalize() method of your class will be called by the garbage collector before an object of your class is destroyed.

A Finalize Class That Overrides the finalize() Method of the Object Class

Demo

class Finalize {
  private int x;

  public Finalize(int x) {
    this.x = x;//w  w w.  j  a  va 2 s .  c om
  }

  public void finalize() {
    System.out.println("Finalizing " + this.x);
  }
}

public class Main {
  public static void main(String[] args) {
    // Create many objects, say 20000 objects.
    for (int i = 0; i < 20000; i++) {
      new Finalize(i);
    }
  }
}

Result