My question is "how many objects are made after String1 s="abc" and String2 s=new String("abc");"
I have also read kaithy seira but I couldnt understand...
I know 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.
Is it for only literals or for both when using new keword
I mean if i made a String using literal and new keyword with same string than how many objects are created.
Yup.. As mentioned in the above post, two distinct objects will exist. But its recommended not to create Strings with "new" constructor, as its better to reuse the "pool" of string if it exists so as to reduce the memory consumption.
Harsha Ka wrote:Yup.. As mentioned in the above post, two distinct objects will exist. But its recommended not to create Strings with "new" constructor, as its better to reuse the "pool" of string if it exists so as to reduce the memory consumption.
That's true, and my suggestion is to use String.valueOf(String). In fact, I'd suggest that you always use a static factory method to construct objects if one is available.
However, the chances of using new causing problems are probably exaggerated. You'd have to be creating many thousands of Strings before it's likely to become an issue; so it's far less likely to cause you problems than using str1 == str2 incorrectly even once.
Look out for my new page on this very subject in the near future.
Isn't it funny how there's always time and money enough to do it WRONG?