English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How many methods can make an object meet the GC conditions in Java?

The process of destroying unreferenced objects is calledGarbage Collection (GC). Once the object is dereferenced, it is considered as an unused object, thereforeJVM will Automatically destroy the object.

There are several methods to make an object eligible for GC.

By removing the reference to the object

Once the purpose of creating an object is achieved, we can set all available object references to " null ".

Example

public class GCTest1 {
   public static void main(String [] args){
      String str = "Welcome to w3codebox"; // String object referenced by variable str 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);
   }
}

Output Result

str eligible for GC: null


By reallocating the reference variable to another object

We can make the reference variable refer to another object. Decouple the reference variable from the object, and set it to refer to another object, so that the object referenced by the previous reference can be used by GC.

Example

public class GCTest2 {
   public static void main(String [] args){
      String str1 = "Welcome to w3codebox";
      String str2 = "Welcome to Tutorix"; // String object referenced by variable str1 and str2 and it is not eligible for GC yet.
      str1 = str2; // String object referenced by variable str1 is eligible for GC.
      System.out.println("str1: " + str1);
   }
}

Output Result

str1: Welcome to Tutorix