The process of destroying unreferenced objects is called Garbage Collection (GC). Once an object is no longer referenced, it is considered unused and therefore JVM automatically destroys the object.
There are many ways to make an object eligible for GC.
Once the purpose of creating the object is achieved, we can set all available object references to "null".
public class GCTest1 { public static void main(String [] args){ String str = "Welcome to TutorialsPoint"; // String object referenced by variable <strong>str </strong>and it is not eligible for GC yet. str = null; // String object referenced by variable str is eligible for GC. System.out.println("str eligible for GC: " + str); } }
str eligible for GC: null
us You can make a reference variable refer to another object. Decouple the reference variable from the object and set it to refer to another object, so the object referenced before the reallocation is eligible for GC.
public class GCTest2 { public static void main(String [] args){ String str1 = "Welcome to TutorialsPoint"; String str2 = "Welcome to Tutorix"; // String object referenced by variable str1 and str2 and is not eligible for GC yet. str1 = str2; // String object referenced by variable str1 is eligible for GC. System.out.println("str1: " + str1); } }
str1: Welcome to Tutorix
The above is the detailed content of How many ways are there to make an object eligible for garbage collection in Java?. For more information, please follow other related articles on the PHP Chinese website!