- You can request JVM to free up some memory which is no longer in use by garbage collection.
- it is a process of freeing up memory from heap .
Making object garbage eligible:
example : Car carObj= new Car();
- nulling the reference eg: carObj=null;
- assigning a reference to another:
- eg: Car carobj2= new Car() ; carObj1 ==carObj2
- By anonymous object etc. eg. new carObj();
Garbage collection in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class DemoGarbage{ //The finalize() method is invoked each time before the object is garbage collected public void finalize() { System.out.println("garbage collected !!"); } public static void main(String args[]) { DemoGarbage obj1=new DemoGarbage(); DemoGarbage obj2=new DemoGarbage(); obj1=null; obj2=null; System.gc(); // request jvm for garbage collection } } |
In above code, System.gc() will make request JVM to run garbage collection.
The finalize() method is invoked each time before the object is garbage collected.
Output:
1 2 |
garbage collected !! garbage collected !! |