logo
Java Garbage Collector
Garbage collector
garbage collector is destroying the useless object and it is a part of the jvm.
To make elgible objects to the garbage collector
whenever we are assigning null constants to our objects then objects are elgible for gc(garbage collector)
class Test 
{ 
public static void main(String[] args) 
{ 
Test t1=new Test(); 
Test t2=new Test(); 
System.out.println(t1); 
System.out.println(t2); 
t1=null;//t1 object is elgible for Garbage collector 
t2=null;//t2 object is elgible for Garbage Collector 
System.out.println(t1); 
System.out.println(t2); 
} 
};
Output :
ee.Test@6eb38a
ee.Test@1cd2e5f
null
null
gc() :
1) internally the garbage collector is running to destroy the useless objects. 

2) by using gc() method we are able to call Garbage Collector explicitly by the developer. 

3) gc() present in System class and it is a static method.
Syntax: System.gc(); 

4) Whenever garbage collector is destroying useless objects just before destroying the objects the garbage collector is calling finalize() method on that object to perform final operation of particular object.
if the garbage collector is calling finalize method at that situation exception is raised such type of exception are ignored.
class Test 
{ 
public void finalize() 
{ 
System.out.println("freetmielearn"); 
int a=10/0; 
} 
public static void main(String[] args) 
{ 
Test t1=new Test(); 
Test t2=new Test(); 
t1=t2; 
System.gc(); 
} 
};
Output :
freetmielearn
If user is calling finalize() method explicitly at that situation exception is raised.
class Test 
{ 
public void finalize() 
{ 
System.out.println("freetmielearn"); 
int a=10/0; 
} 
public static void main(String[] args) 
{ 
Test t1=new Test(); 
Test t2=new Test(); 
t1=t2; 
t2.finalize(); 
} 
};
Output :
freetmielearn