In java, garbage means unreferenced objects. The unused memory automatically collected by which process is known as Garbage Collection. That means it is a process to destroy the unused memory. In JAVA it is performing automatically. So in JAVA memory management is better
Advantage of Garbage Collection
There are many ways:
Customer c=new Customer();
c=null;
Customer c1=newCustomer();
Customer c2=new Customer();
c1=c2;//now the first object referred by c1 is available for garbage collection
new Customer();
when finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created any object without new, you can use finalize method to perform cleanup processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread calls the finalize() method before object is garbage collected.
public class GarbageDemo{ public void finalize() { System.out.println("Silan Software"); } public static void main(String[]args) { GarbageDemoob1= new GarbageDemo(); GarbageDemoob2= new GarbageDemo(); ob1= null ; ob2= null ; System.gc(); } }
Output
object is garbage collected
object is garbage collected
Note: Neither finalization nor garbage collection is guaranteed.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc