Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Each call to StringBuffer#toString and StrinBuilder#toString returns new instance or instance from string pool?

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)

like image 953
Jeevan Avatar asked Dec 27 '22 00:12

Jeevan


1 Answers

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

like image 187
Suresh Atta Avatar answered Apr 27 '23 11:04

Suresh Atta