The difference between string, StringBuffer, StringBuilder in Java

Source: Internet
Author: User

1. Variable and immutability

The string is immutable, it is a character array that holds the value of the object and is declared as the final type, so the string object is a sequence of immutable characters.

    Private final char value[];

Both StringBuffer and StringBuilder are variable sequences of characters, which are also saved by a character array.

    Char value[];

2. Thread is secure

String is final type, immutable, so it must be thread safe .

StringBuffer adds a synchronous lock to a method that adds a synchronous lock or a call, so it is thread-safe . The source code is as follows:

Public synchronized String substring (int start, int end) {
Return super.substring (start, end);
}

Public synchronized StringBuffer append (String str) {
Super.append (str);
return this;
}

The method in StringBuilder does not implement the synchronous lock function, so it is non-thread safe .

3.StringBuffer and StringBuilder of the same point

both inherit the abstract class Abstractstringbuilder and inherit the basic operations that define some strings, such as expandcapacity, append, insert, indexof, and so on.

The only difference between an abstract class and an interface is that the abstract class defines some common methods in the subclass, and only a few new operations are added to the subclass. The interface is simply a declaration of the definition and method of a constant, and the subclass implementation must implement all the methods in the interface.

If it is only a single thread recommended to use StringBuilder, it is more efficient than stringbuffer.

  

The difference between string, StringBuffer, 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.