In: Computer Science
Garbage collector works in following condition:
1.
Employee john = new Employee()
john=null;
2.
Employee c1 =new Employee()
Employee c2 = new Employee()
c1=c2;
3.
new Employee(); //anonymous object
Please create a class /classes in java which contains examples related to above 3 conditons.
In java, when object has no reference or unreferenced (means it is no longer usable) the memory given to these objects can be made avilable or free. and all this is done automatically by Garbage collector in java.
Here is screenshot of Java code:
Here is the Output:
Here is the code:
public class Employee {
// finalize method is used to perform cleanup
activities
// we can make finalize public also
protected void finalize()
{
System.out.println("Garbage collector collected the object");
}
public static void main(String[] args) {
Employee john = new
Employee();
john=null; //object john
has no vlaue so space allocated to it can be freeup
Employee c1 =new
Employee();
Employee c2 = new
Employee();
c1=c2; //now c1 has
value of c2 so previous allocated space can be freeup
new Employee(); // this
anonymous object is of no use so it can also freeup
System.gc(); //this
method is used to invoke the Garbage Collector
}
}