When the
compiler encounters a String literal, it checks the pool to see if an identical String
already exists. If a match is found, the reference to the new literal is directed to the
existing String, and no new String literal object is created. (The existing String simply
has an additional reference.)
does this mean that only those strings are checked which hava reference ? what about the lost objects which they dont have nay
reference pointing to them?
String s = new String("abc"); // creates two objects,
// and one reference variable
In this case, because we used the new keyword, Java will create a new String object
in normal (nonpool) memory, and s will refer to it. In addition, the literal "abc" will
be placed in the pool.
>> this is alittle bit confusing could somebody please clear it up for me? does this mean s refers to two objects? why do we need to create two objects ? so what happens to the object which is in normal (nonpool) memory when we want to alter the objec refered to by s ? will it be aaboned as well? at last isn't it redundancy?
...Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means that they always have a reference to them and are, therefore, not eligible for garbage collection.
Since Strings are immutable, multiple references can share the same actual value. This is done to save resources. However, using the new keyword manually creates unique objects and is redundant like you say.
I think creating String s = new String("abc") should not put put String "abc" into String pool , otherwise why do we need intern() ? Please correct me if I am wrong.
Sounds like intern() is used for specialized comparison of Strings. I must not be using intern() properly because it looks to me like it slows things down.
If you are perform intern() on String object jvm checks that String object content is available in any literal object. if it present means return that literal object reference otherwise it create one literal object and that reference will return.
in the above example is the object eligible for garbage collection before the main completes? i think it shouldn't be because the literal "abc" will be placed in the pool and hence it will alwyas has a reference, am i right?
objects are always created in heap memory only. String constant pool doesn't contain objects it contain literal object references only so one object is eligible for GC. literal object present in heap and it's reference is in string constant pool memory.