Every call to StringBuffer # toString and StrinBuilder # toString returns a new instance or an instance from the string pool?

My question is if I use StringBuffer (or StringBuilder), and if I call the toString method on the instance several times. Will a StringBuffer return a new instance of String every time, or will it return a String from a string pool? (assuming I didn't make any changes to the StringBuffer between calls)

+4
source share
3 answers

Only string literals are placed in a string constant pool. for example String s = "abc"; will be in the string pool, and String s = new String("abc") will not. toString() method created a new row, so the returned row will not be from the literal pool.

Whenever the toString() method is encountered, a new line is created.

Objects of empty String objects will be passed again only if you do the following.

 String s = "abc"; String s1 = "abc"; 

This means that both control variables s and s1 will refer to the same abc literal in the constant pool.

Here you can find useful articles on the string constant pool. http://www.thejavageek.com/2013/06/19/the-string-constant-pool/

+4
source

According to docs toString () 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. Then this line is returned. Subsequent changes to the line buffer do not affect the contents of the line.

So, the New String object is allocated and initialized .

String objects allocated using the new operator are stored on the heap, and there is no exchange of content for the same content, where String literals are stored in the shared 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

+4
source

Yes, calling the toString method StringBuffer and StringBuilder will create a new string object each time, since these methods use the new keyword to return the string.

Here is the code for toString from the StringBuffer class:

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

Here is the toString method from the StringBuilder class:

 public String toString() { // Create a copy, don't share the array return new String(value, 0, count); } 
+1
source

Source: https://habr.com/ru/post/1492058/


All Articles