Question

In a Java setter method that assigns a new Object to a field such as:

public class MyClass
{
     private String s;
     public void mySetter(String newS) {
          s = newS;
     }
}

Does the previous String s get garbage collected after mySetter is called or should I null out s before I assign it to the new value?

public class MyClass
{
     private String s;
     public void mySetter(String newS) {
          s = null;
          s = newS;
     }
}
Was it helpful?

Solution

Does the previous String s get garbage collected after mySetter is called or should I null out s before I assign it to the new value?

If your previous String s is not referenced anywhere then it will be. But it won't happen immmedialtely after mySetter is called. No need to set it to null.

OTHER TIPS

no need to null out, the garbage collector will find the string if no one else references it.

You don't have to do s = null; part. In Java a variable is in fact a reference to physical object in RAM memory. So when you do s = newS; you make a variable s point to a new object in RAM and the old object is no longer referenced by any of your variables and will be garbage collected.

Garbage collection will only happen when memory space is required by JVM

so in your case it will not be garbage collected as soon as your method gets called.

for more already an answer here

Also while assigning string to another value, you need not to set it to null first, as when you assign a new value to string means that now your reference variable is not pointing to previous value of the String object but to the new one and Java provides you the flexibility of not worrying about GC like other programming language. So don't try doing GC, Java can take care of it for you

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top