Differences between String, StringBuffer, and StringBuilder in Java,

Source: Internet
Author: User

Differences between String, StringBuffer, and StringBuilder in Java,
Differences between String, StringBuffer, and StringBuilder in Java 1. variable or not

The String class uses character arrays to save strings. Because there is a "final" modifier, the String object is immutable.

    /** The value is used for character storage. */    private final char value[];

 

StringBuffer and StringBuilderAll are inherited from the AbstractStringBuilder class. In AbstractStringBuilder, character arrays are used to save strings, but there is no "final" modifier, so the two objects are variable.

    /**     * The value is used for character storage.     */    char[] value;

 

2. multi-thread security?

The object in String is immutable, so it can be understood as a constant.Thread-safe.

AbstractStringBuilder is a common parent class of StringBuffer and StringBuilder. It defines some basic string operations, such as append, insert, and indexOf.

StringBuffer adds a Synchronous lock (synchronized) to the method, so it isThread-safe. See the following source code:

1     public synchronized StringBuffer append(String str) {2         toStringCache = null;3         super.append(str);4         return this;5     }

StringBuilder does not apply a synchronization lock to the method, so yesNon-thread-safe. Source code:

1     public StringBuilder append(String str) {2         super.append(str);3         return this;4     }

 

3. Commonalities Between StringBuffer and StringBuilder

StringBuffer and StringBuilder have common parent classes AbstractStringBuilder (Abstract class).

The StringBuffer and StringBuilder Methods call the public methods in AbstractStringBuilder. The above two source code sections call the super. append (str); only the StringBuffer will add the synchronized keyword to the method for synchronization.

Finally, if the program is not multi-threaded, StringBuilder is more efficient than StringBuffer.

 

 

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.