In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
There are many ways:
Employee e=new Employee(); e=null;
Employee e1=new Employee(); Employee e2=new Employee(); e1=e2;//now the first object referred by e1 is available for garbage collection
new Employee();
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
public class TestGarbage1{ public void finalize(){System.out.println("object is garbage collected");} public static void main(String args[]){ TestGarbage1 s1=new TestGarbage1(); TestGarbage1 s2=new TestGarbage1(); s1=null; s2=null; System.gc(); } }