My question is if am using a StringBuffer(or StringBuilder) and if I call toString method on the instance multiple times. Will StringBuffer return new instance of String each time or it returns String from String pool? ( assuming I have not made any change to StringBuffer in between the calls)
Only string literals are placed in String constant pool. e.g. String s = "abc";
will be in string pool while String s = new String("abc")
will not be. toString()
method created a new string so the string returned will not be from literal pool.
Whenever toString()
method is encountered, a new String will be created.
String constant pool objects will be referred once again only if you do as follows.
String s = "abc";
String s1 = "abc";
This means both reference variables s
and s1
will refer to same abc
literal in the constant pool.
You can find a useful articles regarding the string constant pool here. http://www.thejavageek.com/2013/06/19/the-string-constant-pool/