I have two questions to ask-
1.In a StringBuilder class,when we create it's object,we pass a string literal as parameter.Does this literal also goes in the constant pool?
2.During chaining of methods in case of Strings,such as "x.concat("def").toUpperCase().repalce('x',"X")",if the temporary objects created are lost,how come methods are invoked on them when they are lost.i.e if x.concat("def") creates a object which is lost,how come toUpperCase() works?
Please pardon me if i have asked a silly question,and be patient to look at my problem.
1. The String literal goes in the pool when the class is loaded, along with any and all other String literals in the class. That the String literal is used as the argument to a StringBuilder constructor is irrelevant.
2. You need to explain what you mean by 'lost'. The chained method is invoked on the returned object from the preceding method. After execution, there is no longer a reference to the intermediate values, so they are eligible for GC.
There are no new questions, but there may be new answers.
Thanks for the quick reply,
Actually what i am concerned about is the number of objects created.
StringBuilder build=new StringBuilder("abc");
Now,how many objetcs?
And one more thing,if again "abc "is created in the string constant pool,and i use several such operations,won't it again cause a memory wastage due to excessive string literals in string constant pool?
Sudhanshu Mishra wrote:And one more thing,if again "abc "is created in the string constant pool,and i use several such operations,won't it again cause a memory wastage due to excessive string literals in string constant pool?
The whole point of the string pool is to reuse String objects. If you use the same string literal multiple times in your source code, then they will all refer to the same String object that's in the string pool. For example: