The difference between string, StringBuffer, StringBuilder in Java

Source: Internet
Author: User
Tags array length stringbuffer

Java contains three classes of String,stringbuffer and StringBuilder to encapsulate strings

0. Improper use
String result = "";    for (String s:hugearray) {      = result + s;  }  

Do not use the String class "+" for frequent splicing , because that performance is very poor, you should use the StringBuffer or StringBuilder class, which is a more important principle in Java optimization

1. Strings encapsulated in the string class are immutable

The string is made up of several characters in a linear arrangement, and the key source code for the string class is as follows

 Public Final class String     implements java.io.Serializable, comparable<string>, charsequence {    /**   */   privatefinalchar value[];   Final type char array // omit other code ... ...}

Because of the "final" modifier, strings that can be encapsulated in the string class are immutable . Then how to delete the change is how to achieve it? Here is the key source of string interception

 PublicString substring (intbeginindex) {        if(Beginindex < 0) {            Throw Newstringindexoutofboundsexception (Beginindex); }        intSublen = Value.length-Beginindex; if(Sublen < 0) {            Throw Newstringindexoutofboundsexception (Sublen); }       //when the original string is intercepted (Beginindex >0), the result returned is the newly created object        return(Beginindex = = 0)? This:NewString (value, Beginindex, Sublen); }

You can see that the intercept source was generated by a new string object.

Therefore, a lot of temporary variables are generated when a large number of "insert" and "delete" operations are performed on strings of string type.

Since the string encapsulated by the string class is immutable, there should be a class to encapsulate the mutable array. The answer is yes, the StringBuilder and StringBuffer encapsulation classes are mutable.

2. How to do package array variable

Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder abstract class, and the key code of the Abstractstringbuilder is to use a character array to save the string as follows

Abstract classAbstractstringbuilderImplementsappendable, charsequence {/*** The value is used for character storage. */    Char[] value;//An array of type char, not a final type, which differs from the string class    /*** This no-arg constructor are necessary for serialization of subclasses. */Abstractstringbuilder () {}/*** Creates an abstractstringbuilder of the specified capacity. */Abstractstringbuilder (intcapacity) {Value=New Char[Capacity];//constructed an array of length capacity size    }//other code omitted ......}

The StringBuffer class implementation code is as follows

 Public Final classStringBufferextendsAbstractstringbuilderImplementsjava.io.Serializable, charsequence{/*** Constructs a string buffer with no characters in it and an * initial capacity of characters. */     PublicStringBuffer () {Super(16);//Create a char array with a default size of 16    }    /*** Constructs a string buffer with no characters in it and * the specified initial capacity. *     * @paramcapacity the initial capacity. * @exceptionNegativearraysizeexception if the {@codecapacity} * argument is less than {@code0}.*/     PublicStringBuffer (intcapacity) {        Super(capacity);//Custom Create a char array of size capacity    }//omit other code .........

You can see that the default size of the StringBuffer create string object is 16, and of course you can pass in the array size.

Below is a list of the uses of StringBuffer

 Public class test{  publicstaticvoid  main (String args[]) {    new StringBuffer ("Hello");    Sbuffer.append ("");    Sbuffer.append ("World");    System.out.println (Sbuffer);   }}

Output

Hello World

Below see the source analysis under the Append function, see how to do the length variable

 Publicabstractstringbuilder Append (String str) {if(str = =NULL)            returnAppendnull (); intLen =str.length (); //call the following ensurecapacityinternal methodEnsurecapacityinternal (Count +Len); Str.getchars (0, Len, value, count); Count+=Len; return  This; }Private voidEnsurecapacityinternal (intminimumcapacity) {        //overflow-conscious Code        if(Minimumcapacity-value.length > 0)           //Call the Expandcapacity method below to implement the "Capacity expansion" featureexpandcapacity (minimumcapacity); }   /*** This implements the expansion semantics of ensurecapacity with no * size check or synchronization. */    voidExpandcapacity (intminimumcapacity) {       //The extended array length is extended by twice times the length of the array before "extended" plus the 2 byte rule .        intnewcapacity = value.length * 2 + 2; if(Newcapacity-minimumcapacity < 0) newcapacity=minimumcapacity; if(Newcapacity < 0) {            if(Minimumcapacity < 0)//Overflow                Throw NewOutOfMemoryError (); Newcapacity=Integer.max_value; }        //The value variable points to the new char[] object returned by the arrays, thus achieving the "Capacity expansion" featureValue =arrays.copyof (value, newcapacity); }

You can see the space extension roommate copyof function implementation:

 Public Static Char [] copyOf (charint  newlength) {        // creates a char array of length newlength, which is the char after "expansion" Array, and as the return value        charnewchar[newlength]        ; 0, copy, 0,                         math.min (Original.length, newlength));         return copy; // returns the array variable after "expansion"    }
3. Difference between StringBuilder and StringBuffer

Abstractstringbuilder is the common parent of StringBuilder and StringBuffer, and defines some basic operations for strings, such as expandcapacity, append, insert, indexof, and other public methods , the methods of StringBuilder and StringBuffer are basically consistent, but the StringBuffer class method has a synchronized keyword before it, that is, StringBuffer is thread-safe.

 Public synchronized StringBuffer Reverse () {    Super. Reverse ();     return  This ;}  Public int indexOf (String str) {    return indexOf (str, 0);        // There is a public synchronized int indexOf (String str, int fromIndex) method }

(1) The Append,insert,delete method is most fundamentally called the System.arraycopy () method to achieve the goal

(2) The substring (int, int) method is used to achieve the purpose by re-using the new String (value, start, End-start). Therefore, StringBuilder and string are basically no different when performing substring operations.

4. Usage Scenarios

StringBuffer is preferred if the insert and delete operations of shared variables are involved in a multithreaded environment. If it is non-multithreaded and has a large number of string concatenation, insert, delete operation is preferred StringBuilder. After all, the string class is created by creating temporary variables to achieve string concatenation, memory consumption is not high, how to say StringBuilder is the way to achieve the ultimate operation by JNI.

5. Summary
    • String objects of type string are immutable, and once a string object is created, the series of characters contained in the object cannot be changed until the object is destroyed.
    • StringBuilder and StringBuffer types of strings are mutable, unlike stringbuffer types that are thread-safe, and StringBuilder are not thread-safe
    • StringBuffer is preferred if the insert and delete operations of shared variables are involved in a multithreaded environment. If it is non-multithreaded and has a large number of string concatenation, insert, delete operation is preferred StringBuilder.
    • If you want to manipulate a small amount of data, using string, single-threaded operation of large amounts of data, using StringBuilder, multithreading operations of large amounts of data, with StringBuffer.

The difference between string, StringBuffer, StringBuilder in Java

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.