First thing to say is that garbage collection doesn't happen immediately. So assigning null
to anything does not / cannot cause garbage collection. What is may do is to cause an object to become unreachable ... and that will make it a potential candidate for garbage collection in a future GC run.
Now to your specific examples.
Important Note: the following only applies to older JVMs; i.e. Java 7 update 5 and earlier. In Java 7 update 6, they changed String.substring()
so that the target string and resulting substring DO NOT share the backing array. This eliminates the potential storage leak issue with substring
.
The substring
method doesn't put a reference to the original String in the new String. What it actually does is save a reference to the original String's backing array; i.e the array that holds the characters.
But having said that, assigning null
to samplel
is not sufficient to make the state of the entire original string unreachable. The original String's entire backing array will be remain reachable ... and that means it won't be a candidate for garbage collection.
But there is another complication. You set sample1
to a String literal, and the String object that represents a String literal is always reachable (unless the entire class gets unloaded!)
But by explicitly defining samplel as null, will sample1 and sample2 be available for garbage Collection?
The original sample1
object will remain fully reachable, and sample2
will remain be reachable unless that variable goes out of scope.
If sample1
had not been a literal and there were no other references to it, then the answer would be different. The sample1
object would be unreachable, but its backing array would still be reachable via sample2
.
In your second example, copying the substring causes a new String to be created. And it is guaranteed that the new String won't share the backing array with the original String and the temporary substring. In that case, assigning null
is unnecessary.
Will now both sample1 and sample2 be available for garbage Collection?
The answer is the same as for the above for the case where sample1
is a literal.
If sample1
is not a literal and there are no other references to it, then sample1
and the temporary substring would now be unreachable.
I just want to know where does String constructor be helpful.
In theory it will be.
In practice it depends on whether the references are still reachable when the GC eventually gets around to looking ... and also on whether the Strings in question are large enough and numerous enough to have a significant impact on memory usage.
And in practice, that precondition is usually NOT satisfied and creating a fresh String like that usually does NOT help.