Home >Java >javaTutorial >How many ways are there to make an object eligible for garbage collection in Java?

How many ways are there to make an object eligible for garbage collection in Java?

PHPz
PHPzforward
2023-09-10 11:57:02776browse

How many ways are there to make an object eligible for garbage collection in Java?

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.

By dereferencing the object

Once the purpose of creating the 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 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);
   }
}

Output

str eligible for GC: null

By reassigning the reference variable to another object

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.

Example

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);
   }
}

Output

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete