Java Destructor – finalize()

Java Destructor finalize()
Java Destructor finalize()

The aim of destructor in any OOPs language is:

  1. Free up the memory (c++ suffer from memory allocation / deallocation)
  2. Clean up any other resources (like closing of open file stream)

Java take cares of all and hence there is no destructor in Java. (With the help of Garbage collection)
but still if you want to perform some additional tasks, then you can use the finalize() method of java.

But, we can’t rely on finalize() as it depends on GC. Sometimes, GC may never be invoked during the lifetime of the program. A good idea is to implement a method, say cleanUp() which does, any special processing required, ofcourse, other than freeing up memory. The programmer should call this method at the approppriate place in the program. That is the only way to make sure your program works correctly.

Example code of finalize in java:

class Thing {

	public static int number_of_things = 0;
	public String what;

	public Thing (String what) {
	        this.what = what;

	protected void finalize ()  {

public class TestDestructor {
	public static void main(String[] args)
		Thing obj = new Thing("Test App");



  1. Yes this is the only way i could cleanup my OpenGL textures. on every CTOR the reference counts are incremented and on finalized they are decremented. upon count == 0, i release those textures. Anyway GC saves us from a lot of trouble, but no destructor is very compromising as well.

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.