The difference between string, StringBuffer, and StringBuilder in Java

Source: Internet
Author: User
Tags stringbuffer

In programming, for string concatenation we can use the string class overloaded with + or concat (str), stringbuffer append (str), StringBuilder append (str). So what is the difference between the three?

One: String

Characteristics of the 1:string class

1) string is a final class: So the string class cannot be inherited. Similarly, the value of a string object cannot be changed;

2) Comparison of creation methods of string objects (principle comparison):

When the JVM loads the run class file, the constants (symbol references, string literals, and so on) that appear in the byte file are categorized in the constant pool in the method area. Where the string literal constants that appear in the source code are saved in the Constant_string_info constant table . Then, depending on the creation method, there will be different content assignments, as follows:

1, literal constant way to create a string variable : string str1= "string";

String str2= "string";

The above creates two string references, all pointing to strings of the same content. We know that when the class is loaded, the string constants are stored in the Constant_string_info constant table , and the same string content is stored only once (we call the string in the Constant table "detention string"). Therefore, the above two string references all point to the same address (the same detention string) in the Constant_string_info constant table . So, here Str1==str2 returns True. (Another: There is no string object created because there is no memory allocated in the heap)

2. Create a string Objectwith the New keyword: string str1=new string ("string");

String Str2=new string ("string");

Class at load time, the string constants appearing in the source code are placed in the Constant_string_info constant table, so: the same "string" constant value in the above two statements is placed in the same place in the string constant table. Then, when the two statements are executed, the string objects str1 and str2 are created separately in the heap according to the new keyword, and both objects hold a value of "string" in the heap. That is, there are three places in the JVM where the same string value exists: the detention string in the constant table, the heap space of the Str1 object, and the heap space of the STR2 object. Therefore, the STR1==STR2 returned here is false. Call the string class to override the Equals () method to compare the values of two objects to return true.

3. String "Object" created by the Intern () method: String str1= "string";

String Str2=new string ("string"). Intern ();

Intern (): When there is a string in the constant pool string constant table (with the same content) as "string" (detention string), the address of the detention string is returned directly, assigned to STR2 (no new object is created at this time);

If the constant pool does not have the same detention string as "string", then "string" is added to the constant pool (becomes a detention string for return use for the next intern ()), and a string object is created in the heap and a reference to the object is returned (a new object is created at this time);

So, here Str1==str2 returns True.

Thus, theintern () method can be used to avoid the creation of duplicate content string objects , which deserves our attention.

2:string Overloaded + working principle

When you use the string class to overload the + concatenation of strings, you can follow the other data types before and after the +, not necessarily the string types. Other types of data are automatically converted to a string type "to high."

The overloaded + operator, in fact, creates a StringBuffer or StringBuilder object, joins the string using the Append method, and finally calls the ToString method to return string strings.

Note the two cases of using the + stitching string:

2.1) use + to stitch two string variables: string str1= "str";

String str2= "ing";

String str=str1+str2;

String str1_2= "string";

Parse: Here with + splicing is two string variable, so will first create a stringbuffer/stringbuilder, and then append (str1). Append (str2) splicing str1 and str2 together, and finally through ToString ( A new string object is generated and the reference is returned, assigned to Str. So, the str==str1_2 result here is false. a new String object is created here.

2.2) with + splicing two string literal: string str1= "str" + "ing";

String str2= "string";

Parsing: When stitching two string literals with +, the JVM automatically saves the combined values of these two literals as a completed string constant value into the constant pool's string constant table. Therefore, the STR1==STR2 result here is true. There is no new string object created, only the concatenation result is returned as the save address of the detention string.

Concat (str) stitching strings in 3:string

Unlike the + can splice other data types, concat () can only block the contents of a string type behind the caller.

 public   string concat (String str) { Span style= "color: #0000ff;"      >int  otherlen = Str.length ();  if  (Otherlen = = 0) { return  this  ;  char  buf[] = new  char  [Count + Otherlen];      GetChars ( 0, Count, buf, 0 0 return  new  String (0, Count + Otherlen, buf); }

As we can see, the concat () stitching string is created by creating a new char[] character array, converting two strings into char after a new array exists, and finally creating a new string object with char[].

Two: StringBuilder

1:stringbuilder is a non-thread-safe final class that cannot be inherited

2:stringbuilder's Append () Working principle

Public StringBuilder Append (String str) {        Super. Append (str);        This ;}    

StringBuilder is called the Append method of its parent class, we look at the source code:

 Publicabstractstringbuilder Append (String str) {if(str = =NULL) {str= "NULL"; }        intLen =str.length (); if(len = = 0) {            return  This; }        intNewcount = count + len;//statistics concatenation after string length        if(Newcount >value.length) {expandcapacity (newcount);//If the stitching result is greater than the char[used], the expansion        }       //GetChars the concatenation of strings to char[]Str.getchars (0, Len, value, count); Count= Newcount;//Update char[] The length of the string saved        return  This; }

When you use StringBuilder to stitch a string, you actually create a char[] array at the bottom, and then add the string you want to splice to char[] by char[]. Finally, when the final stitching result is generated by ToString (), it is implemented by the return new String (char[]).

Three: StringBuffer

1:stringbuffer is a thread-safe final class that cannot be inherited.

2:stringbuffer's Append () Working principle

Synchronized stringbuffer append (String str) {    Super. Append (str);        This ;}    

As you can see, the Append of StringBuffer is also implemented by invoking the Append method of the parent class Abstractstringbuilder, which is the same principle as StringBuilder. The only difference is that a syncrhoized keyword modifier append () method is added to ensure thread synchronization.

Four: Performance comparison and selection of three

1: Performance: generally stringbuilder>stringbuffer>string

From the above four (in fact, should be said to be five, + divided into string constants and the concatenation of the variables of the two) string stitching, In addition to the concatenation of string constants is to return the address of the detention string , the other four kinds (STR1+STR2, Str1.concat (STR2), Builder.append (STR1). Append (str2), Buffer.append (str1) append (str2)) are all using StringBuilder, Or the StringBuilder of the parent class -- Create a char array, save the content that needs to be stitched into a char array, and finally create a new string object from the char array.

The main reasons for the three performance differences are:

When a string variable is spliced with string +, each splice creates a StringBuilder, stitching it through the append () method, and returns a new string object. Then continue stitching the next variable. This results in a duplicate creation of the StringBuilder object with poor performance. when using concat (), the concatenation of each of the two strings will create a char[] for the content stitching and return a new string object as a result, repeated calls to Concat () will cause duplicate creation char[] and a new string object, Performance is low.

StringBuilder does not create a stitching result before calling ToString (), and the underlying char array is automatically expanded until the concatenation string is fully stored in the char array, and the new string object is created and returned after the call to ToString (). This avoids duplicate creation and improves efficiency.

StringBuffer is syncrhoized to append () because of the use of the lock, which results in a slightly lower performance than StringBuilder.

2: Selection under different scenarios

Concatenation of two string literals, with the + operator;

Stitch two string variables in single thread, with StringBuilder;

Multi-thread splicing two string variables, with StringBuffer;

The difference between string, StringBuffer, and StringBuilder in Java

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.