问题
As we know when ever we are creating String object like String value = new String("ABC");
then new String
object will be created and when we use value variable again as value="xyz"
then a new String
object will be created.
So my question is that at which point previously created String
object will be garbage collected?
回答1:
Whenever you call new
in JAVA it create an object in heap but in case of String literals, it will go into the String Constant Pool.
Sample code:
String value = new String("ABC");
value = "xyz";
Now in the above sample code "ABC" and "xyz" string literals will go to the String Constant Pool and will not be garbage collected but finally value
is referring to "xyz" from the String Constant Pool.
So basically there are 3 objects, 2 in the String Constant Pool and 1 in the heap.
at which point previously created String object will be garbage collected?
The object is created by new
will be garbage collected once its scope/life is finished or there is no reference to access it. It's applicable similarly for all the objects including String as well.
Since the value
reference will be pointed to the existing object with the value "xyz" within the string constant poll in the next line, so that previously created object using new
in the heap is eligible for garbage collection but not "ABC" string literal that is still in the string constant pool.
Try to visualize it.

Read more...
回答2:
Just like other Objects for String also JVM follows same approach , once application looses its reference it is eligible for garbage collection.
For your case new String("ABC") is not interned so it will not go in String pool and when you create String for "ABC" again a new Object is created in heap.
String value = new String("ABC");
value = new String("ABC");
In above example after executing both lines first object is eligible for garbage collection.
String created by value="xyz" is interned also so it will be created in String pool and when u create String using value="xyz" the previous object is returned from String pool.
String value ="xyz";
value ="xyz";
In above example after executing both lines only one Object is created for which we have reference also so it is not eligible for garbage collection.
More details on when does a String go in String pool.
Yes Cases
- new String() always creates new Object. It is not interned so you can not take it back from memory.
No Cases
- String a ="aa"; if already available it retrieves from pool , when
not available it creates new object which is interned also.
- new String().intern() or "aa".intern(); if already available it retrieves from pool , when not available it creates new object which is interned also.
- Concatenation ( "a" + "b" )
来源:https://stackoverflow.com/questions/24711100/how-string-object-is-garbage-collected-in-java