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" )