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");

Categorized as JAVA Tagged

How to Install java on Ubuntu 10 and Ubuntu 11

Run below command on the terminal of ubuntu to install the JAVA.
Ubuntu 10 :
	$ sudo add-apt-repository "deb partner"
	$ sudo apt-get update
	$ sudo apt-get install sun-java6-jdk
	$ sudo apt-get install sun-java6-jre

Ubuntu 11:

sudo add-apt-repository ppa:ferramroberto/java
sudo apt-get update
sudo apt-get install sun-java6-jdk sun-java6-jre
sudo update-alternatives --config java