Finalize Method in Java

In this post we will learn about finalize() method. Few facts about finalize() method that we should be aware of are listed below:

It is a method of object() class and we can override and overload this method.

This method is called by garbage collector whenever object is removing from the memory by the garbage collector.

In order to execute some bunch of statements, garbage collector coming to heap for removing abandoned objects and it scans the heap in order to find out abandoned objects. Before all this process garbage collector call finalize() method every-time.

finalize() method do house keeping activity.

We can use finalize() method n number of times as finalize method is empty. Garbage Collector comes once in a while in memory management. It gets less priority because it is a daemon thread.

Let us go through simple lines of code to understand the usages of finalize() method.

[java]

class E {

@override

protected void finalize() throws Throwable {

System.out.println(“from finalize ” );

}

}

class Manager {

public static void main( String[] args) {

E e1 = new E();

e1=null;

System.gc();

System.out.println( ” done” );

}

}

OUTPUT:

done

from finalize

[/java]

The order of above output may vary.

gc() is a static method inside System class. It is just a request not a command.

Itsourcecode is designed to help those newbie programmers to widen their knowledge and enhance their skills in programming through free source code from different programming languages such as VB.net, PHP, Java, HTML, CSS, etc.