Garbage Collection in Java

Garbage collection is a mechanism to remove objects from memory when they are no longer needed.
Garbage collection is carried out by the garbage collector:

Garbage Collection in Java
Garbage Collection in Java



  1.  The garbage collector keeps track of how many references an object has.
  2.  It removes an object from memory when it has no longer any references.
  3.  Thereafter, the memory occupied by the object can be allocated again.
  4.  The garbage collector invokes the finalize method.


finalize() Method
A constructor helps to initialize an object just after it has been created.
•In contrast, the finalize method is invoked just before the object is destroyed:


  1.  implemented inside a class as:
  2. protected void finalize() { … }
  3.  implemented when the usual way of removing objects from memory is insufficient, and some special actions has to be carried out

Simple Example of garbage collection in java

  1. public class SampleGarbage1{  
  2.  public void finalize(){System.out.println("object is garbage collected");}  
  3.  public static void main(String args[]){  
  4.   SampleGarbage1 s1=new SampleGarbage1();  
  5.   SampleGarbage1 s2=new SampleGarbage1();  
  6.   s1=null;  
  7.   s2=null;  
  8.   System.gc();  
  9.  }  
  10. }