1.

What Are The Different Ways To Make An Object Eligible For Garbage Collection When It Is No Longer Needed?

Answer»
  • Set all available object references to "null" once the purpose of creating object is served.

package com.instanceofjava;

class GarbageCollectionTest1{

public static void main(String [] args){

 String str="garbage COLLECTION interview questions";

// String object REFERENCED by variable str and is not eligible for GC yet.

 str=null;

//String object referenced by variable str is eligible for GC

}

}

  • Make the REFERENCE variable to refer to another object. DECOUPLE the reference variable from the object and set it refer to another object, so the object which was referring to before reassigning is eligible for Garbage Collection

package com.instanceofjava;

 class GarbageCollectionTest2{

public static void main(String [] args){

 String str1="garbage collection interview questions";

String str2="Top 15 garbage collection interview questions";

// 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

 }

}

package com.instanceofjava;

class GarbageCollectionTest1{

public static void main(String [] args){

 String str="garbage collection interview questions";

// String object referenced by variable str and is not eligible for GC yet.

 str=null;

//String object referenced by variable str is eligible for GC

}

}

package com.instanceofjava;

 class GarbageCollectionTest2{

public static void main(String [] args){

 String str1="garbage collection interview questions";

String str2="Top 15 garbage collection interview questions";

// 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

 }

}



Discussion

No Comment Found