If the object is created in heap, it will be cleaned bt garbage collector when there is no reachable reference for the object.
We know String constants are created in String pool if there is no String object present in String pool. My doubt is when the objects in the String pool is cleaned or released from memory? If the objects are continuously getting added to the pool, there might be memory issue at some point of time.
if we consider this point, String s = new String("ABC") is better than String s = "ABC" where in former case when s is made null, the String Object with "ABC" will be eligible for gc where in later case the object will reside in constant pool for 'n' hous.
Henry please correct me if I m wrong..
Well, you're wrong in that in both cases there's a literal "ABC" in the string pool; in the first case, you create a second String on the heap as well.
To answer your original question, Strings in the string pool may be released when, and only when, the classes that defined them are collected. This in turn will happen only if the classloader that loaded the class is itself collected. In general, string literals live as long as the code that uses them. If you have a complex environment like an app server in which classloaders are being created and deleted, then there may be some string pool cleanup that gets done, but otherwise not.
No, String s = new String("ABC") is not better. There is still the String object in the pool that represents the "ABC" string literal that you are using here. In this statement, you are explicitly creating a new String object that copies its contents from the pooled String object. So you'll have two String objects - the one in the pool, and the one you created yourself.
Writing something like String s = new String("...") is never necessary in Java and is always unnecessarily inefficient.
In this statement, you are explicitly creating a new String object that copies its contents from the pooled String object.
To make more clear , even if there is no literal "ABC" exists in String pool, and String s = new String("ABC") is the first statement of the application, then
i) String object "ABC" will be created in String Pool
ii) String Object will be created in heap which copies content from String Pool
So in total 2 objects will be created.. is that correct?