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)
As per docs of toString() of StringBuffer
Converts to a string representing the data in this string buffer. A new String object is allocated and initialized to contain the character sequence currently represented by this string buffer. This String is then returned. Subsequent changes to the string buffer do not affect the contents of the String.
So, A new String object is allocated and initialized.
String objects
allocated via new operator are stored in the heap, and there is no sharing of storage for the same contents, where as String
literals are stored in a common pool.
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
where s1 == s2 == s3 but s4 != s5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With