finalize() Java Destructor

finalize() Java Destructor


About finalize() Java Destructor method

The finalize() method is equivalent to a destructor of C++. When the job of an object is over, or to say, the object is no more used in the program, the object is known as garbage. The process of removing the object from a running program is known as garbage collection. Garbage collection frees the memory and this memory can be used by other programs or the same program further in its execution. Before an object is garbage collected, the JRE (Java Runtime Environment) calls the finalize() method. finalize() method can be best utilized by the programmer to close the I/O streams, JDBC connections or socket handles etc.

Following is the method signature as defined in Object class.

protected void finalize( ) throws Throwable

Notice, the finalize() method is declared as protected. The following program illustrates the usage of finalize() method.


finalize() Java Destructor
Output screenshot on finalize() Java Destructor

d1 != null

When d1 is not equal to null means it is still used in the program; there by println() method is executed.

d1 = null;
if (d1 == null)

d1 object is made null, that is, the d1 object is not referencing any data in the table. It is eligible for garbage collection and thereby the println() method is executed.

super.finalize() method calls finalize() method on the super class objects, if any exist. Garbage collection or finalize() method can not be forced to happen as garbage collection is an implicit behavior of JVM. Different JDKs come with different algorithms of garbage collector, and for this reason, we cannot exactly predict when the garbage collection takes place. But still programmer can advise the garbage collection to take place by calling the following methods; remember it is only an advice but not sure it will happen.

System class comes with the following two methods for garbage collection.

  1. System.runFinalization( ): removes all objects ready of garbage collection.
  2. System.runFinalizersOnExit(true): advice to call finalize() method before garbage collection. This method is deprecated in JDK 1.2.

6 thoughts on “finalize() Java Destructor

  1. Anmol Sharma

    thanks but isn’t there an easier process or say program to help me through with how finalizers really act as destructors ?
    email me the program if possible.
    that will be a great help
    thanks
    – anmol

  2. Praveenkumar

    Hello Sir,

    I am beginner in Java how programmer can utilize finalize() method to close the JDBC, IO connection as u explained above..

Leave a Reply

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