String, StringBuilder, stringbuffer differences in Java

Source: Internet
Author: User

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. Each time a change is made to a string object, it is equivalent to generating a new string object and then pointing the reference to the new string object, the original string object GC is recycled.

Private final char value[];

Both Stringbuider and StringBuffer inherit from the Abstractstringbuider 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 class of Stringbuider and StringBuffer, which defines some basic operations of 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 to a method called. Source:

 Public synchronized StringBuffer reverse () {        super.reverse ();         return  This ;}  Public int indexOf (String str) {    return0);   }

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

StringBuffer is suitable for multi-threaded programs, ensuring synchronization. The StringBuilder is suitable for single-threaded programs and does not guarantee synchronization.

In most cases StringBuilder > StringBuffer > String, it is recommended to use the StringBuilder class.

String, StringBuilder, stringbuffer differences 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.