Aryan PrajapatKnowledge Contributor
What are the possible ways of making objects eligible for garbage collection (GC) in Java?
What are the possible ways of making objects eligible for garbage collection (GC) in Java?
In Java, objects are automatically garbage collected when they are no longer referenced. However, we can also make objects eligible for garbage collection manually using the System.gc() method or by setting the object reference to null.
Consider the following code:
MyObject obj = new MyObject();
obj = null;
System.gc();
In this code, we create an object of the MyObject class and then set the object reference to null. We then call the System.gc() method to request the garbage collector to run.