The difference between string and StringBuffer and StringBuilder in Java

Source: Internet
Author: User

I personally think it is important to understand the difference between string and StringBuffer and StringBuilder. In discussing their differences, we should first know the string in Java.

string is discussed first.

Look at source, you will know an important secret of string:

In string, the inside is a char array to maintain the string, and also defines an index that records the string's starting position in the array, and defines the length of the string. The point is that they are all final types.

    Private final char[] value;    private final int offset;    private final int count;
We know that the final modified variables are immutable. So soon we have to accept the fact that every string in Java is not to be changed. So it is obviously not necessary to change/move the characters within a string. This time will soon find the method in the string replace () is not a string can be changed? To eliminate this question mark, let's look at replace one of the source code:

    Public String replace (char OldChar, char newchar) {        char[] buffer = value;        int _offset = offset;        int _count = count;        int idx = _offset;        int last = _offset + _count;        Boolean copied = false;        while (idx < last) {            if (buffer[idx] = = OldChar) {                if (!copied) {                    char[] Newbuffer = new CHAR[_COUNT];
   system.arraycopy (buffer, _offset, Newbuffer, 0, _count);                    buffer = Newbuffer;                    IDX-= _offset;                    Last-= _offset;                    copied = true;                }                BUFFER[IDX] = Newchar;            }            idx++;        }        return copied? New String (0, Count, buffer): this;    }
The purpose of this method is to replace all the Oldchar in the string with Newchar. It is clear from the above code that when the substitution succeeds it is actually a new string, which is not the original string object.

Also including substring, so other methods, it seems to be changing this string, in fact, is not, and finally all new a string.

So the problem is: often in real development, it is normal to modify a string repeatedly, and sometimes we will do so at high frequency, if each operation is a new string, Obviously not. In this case StringBuffer and StringBuilder appear! The aim is to solve the problem.

Looking at the source code of StringBuffer and StringBuilder will soon find out: In fact, they are almost the same, the only difference is that almost all of StringBuffer's methods are used synchronized to synchronize, So the StringBuffer and StringBuilder differences are thread safety issues.

So the next focus of discussion is how stringbuffer implements the modification of the string.

Both StringBuffer and StringBuilder implement virtual classes: Abstractstringbuilder, where the implementation of key functions is in this virtual class, The string is maintained in Abstractstringbuilder with a char array, and the length of the string is also defined, as shown in the following code:

    Private char[] value;    private int count;
This is not the same as the final char[] value defined in the string. Here's a look at append () the implementation of one of the methods:

    Final void Append0 (string string) {        if (string = = null) {            appendnull ();            return;        }        int length = String.Length ();        int Newcount = count + length;        if (Newcount > Value.length) {            enlargebuffer (newcount);        }        String._getchars (0, length, value, count);        Count = Newcount;    }
The above method is to append a string to StringBuffer or StringBuilder: The first is to determine whether the current string array length is not enough, if not enough to expand, and then copy the string that needs to be appended to value.

It can be found that because the character array value inside the StringBuffer is not final, it can be changed. Instead of a new string object, like a string.

The difference between string and 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: 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.