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

StackOverflow https://stackoverflow.com/questions/17720883

質問

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)

役に立ちましたか?

解決 2

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/

他のヒント

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

Yes calling toString method of StringBuffer and StringBuilder will create a new string object everytime as these methods use the new keyword to return a string.

Here is the code for toString from StringBuffer class:

  public synchronized String toString() {
        return new String(value, 0, count);
    }

Here is the toString method from StringBuilder class:

public String toString() {
        // Create a copy, don't share the array
        return new String(value, 0, count);
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top