Garbage collector

The Garbage Collector
Some object-oriented languages require that you keep track of all the objects you create and that you explicitly destroy them when they are no longer needed. Managing memory explicitly is tedious and error-prone. The Java platform allows you to create as many objects as you want (limited, of course, by what your system can handle), and you don't have to worry about destroying them. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is called garbage collection.
An object is eligible for garbage collection when there are no more references to that object. References that are held in a variable are usually dropped when the variable goes out of scope. Or, you can explicitly drop an object reference by setting the variable to the special value null. Remember that a program can have multiple references to the same object; all references to an object must be dropped before the object is eligible for garbage collection.
The Java runtime environment has a garbage collector that periodically frees the memory used by objects that are no longer referenced. The garbage collector does its job automatically when it determines that the time is right.

“finalize ()” is called by the garbage collector no an object when garbage collection determines that there are no more references to the object. A sub class overrides the “finalize ()” to dispose of of system resource or to perform other clean-up.
Garbage collection is a tool which removes unreferenced object from the memory. When garbage collector remove object from the memory it calls the finalize method.    
There is no guarantee when garbage collector will be invoked and what object referenced will be removed.

Using System.gc ()-         we can invoke garbage collector.

------------------------------->>>>>>>>>>>>
/**Garbage collector dosenot gureenties when and what object will be removed,
but gureenties its will remove unrefrence object only if removes,
by overriding the finalize method **/

public class GarbageDemo
{
public static void main (String...args)
{
int i=0;
while(i++<10000000)
{
MyClass mc=new MyClass();
mc.i=i;
}
System.gc();//Used to invoke garbage collector.
}
}
class MyClass
{
int i=0;
public void finialize()
//This method is called Automatically for clearing unreferenced object.

{
System.out.println("Object removed"+i);
}
}