Home> Java> javaTutorial> body text

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

PHPz
Release: 2023-09-10 11:57:02
forward
705 people have browsed it

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

The process of destroying unreferenced objects is calledGarbage Collection (GC). Once an object is no longer referenced, it is considered unused and thereforeJVMautomatically 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 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); } }
Copy after login

Output

str eligible for GC: null
Copy after login

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); } }
Copy after login

Output

str1: Welcome to Tutorix
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!