The difference between string, StringBuffer, StringBuilder in Java

Source: Internet
Author: User

The difference between string, StringBuffer, StringBuilder in Java


In Java, String, StringBuffer, and StringBuilder are frequently used strings in programming, and the differences between them are frequently asked questions in the interview. Now summarize and see how they differ from the same.

1. Variable and non-changeable

  The string class uses a character array to hold strings, as follows, because there is a "final" modifier, so you know that the string object is immutable.

    Private final char value[];

  Both StringBuilder and StringBuffer inherit from the Abstractstringbuilder class, and in the Abstractstringbuilder, they are also used to hold strings in a character array, as follows, that both of these objects are mutable.

Char[] value;

2. Whether multithreaded security

The objects in string are immutable and can be understood as constants, apparently thread-safe .

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.

StringBuffer is thread-safe because it adds a synchronous lock to a method or a synchronous lock on a method that is called. See the following source code:

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>

1 Public synchronized StringBuffer reverse () {2 Super.reverse (), 3 return this;4}5 6 public int indexOf (String str        ) {7 return indexOf (str, 0); Existing public synchronized int indexOf (String str, int fromIndex) method 8}

650) this.width=650; "src=" Http://common.cnblogs.com/images/copycode.gif "alt=" Copy Code "/>

StringBuilder does not have a synchronous lock on the method, so it is non-thread safe .

3.StringBuilder and StringBuffer in common

StringBuilder and StringBuffer have public parent class Abstractstringbuilder ( abstract class ).

One of the differences between an abstract class and an interface is that the public methods of some subclasses can be defined in an abstract class, and subclasses only need to add new functionality, and do not need to repeat the existing methods, whereas interfaces are simply definitions of the declarations and constants of the methods.

StringBuilder, StringBuffer methods will call public methods in Abstractstringbuilder, such as Super.append (...). Just stringbuffer will add synchronized keywords to the method and synchronize.

If the program is not multithreaded, then using StringBuilder is more efficient than stringbuffer.




4. Comparison of the three in execution speed:StringBuilder > StringBuffer > String

5. Reason for String < (stringbuffer,stringbuilder)

String: Strings constant

StringBuffer: Character creation variable

StringBuilder: Character creation variable

As you can see from the above name, string is a "a constant", which is an immutable object. You may have a question about the understanding of this sentence, such as this code:

1 String s = "abcd";
2 s = s+1;
3 System.out.print (s); // RESULT:ABCD1

We obviously changed the string type of the variable s, why is it not changed? In fact, this is a kind of deception, the JVM is parsing this code: first create the object s, give an ABCD, and then create a new object s used to execute the second line of code, that is, we have not changed the object s before, so we say that the string type is immutable object, because of this mechanism, Whenever you use string to manipulate strings, you are actually constantly creating new objects, and the original objects become garbage collected by GC, so it is conceivable that the execution will be more efficient.

And StringBuffer and StringBuilder are not the same, they are string variables, is a variable object, whenever we use them to operate on a string, it is actually operated on an object, so that it does not like a string to create a number of objects from the inside to operate, Of course the speed is fast.

   6. A special example:

1 String str = "This was only a" + "simple" + "test"; /c7>
3 stringbuffer builder = new StringBuilder ("This was only a") . Append ("simple"). Append ("test");

  

you'll be surprised to find that the build Str The speed of the object is simply too fast, and this time StringBuffer there is no superiority at all in speed. This is actually A trick of the JVM, in fact:

String str = "This was only a" + "simple" + "test";

is actually:

String str = "This was only a simple test";

so it doesn't take much time. But it is important to note that if your string is from another string object, the speed is not so fast, for example:

String str2 = "This was only a";

String STR3 = "simple";

String STR4 = "Test";

String str1 = str2 +str3 + str4;

this time JVM will behave in the original way.

  7.StringBuilder and StringBuffer

StringBuilder: Thread is not secure

StringBuffer: Thread-safe

When we are using a string buffer to be used by multiple threads, the JVM does not guarantee that the StringBuilder operation is safe, although he is the fastest, but can ensure that the StringBuffer can be operated correctly. Of course, most of the time we are in a single-threaded operation, so in most cases it is recommended to use StringBuilder instead of StringBuffer, which is the reason for speed.

Summary of the use of the three : 1. If you want to manipulate a small amount of data with = String

2. Manipulating large amounts of data under a single-threaded operation string buffer = StringBuilder

3. Multi-threaded operation string buffer operation large amount of data = StringBuffer



This article is from the "11100713" blog, please be sure to keep this source http://11110713.blog.51cto.com/11100713/1834141

Differences in 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.