The difference between string, StringBuffer, StringBuilder in Java

Source: Internet
Author: User

String, StringBuffer, and StringBuilder are common string classes in Java , so let's look at the similarities and differences between the three.

One, variable and immutable:

String: Constant, immutable. StringBuffer, StringBuilder are variable character sequences, and are variable.

Second, whether multithreading security:

The objects in string are immutable, equal to constants, and apparently thread-safe .

StringBuffer: multithreading security is supported.

StringBuilder: multithreading security is not supported .

  

Iii. efficiency of implementation:

String, StringBuffer, StringBuilder are used for concatenation of strings: string str1= "ASDFGH"; String str2= "LKJHDSA";

Method One,

Use string:string str3=str1+str2; lowest efficiency .

Method Two,

Use Stringbuffer::str1.append (STR2);  Append using Stringbuiffer's Append () method. High Efficiency (because of its need to achieve thread safety, it is less efficient than StringBuilder. )

Method Three,

Use StringBuilder:str1.append (STR2);  Append using StringBuilder's Append () method. most efficient . (No thread safety issues, so execution is the most efficient)

Summarize:

First, if you want to manipulate a small amount of data, with a string, single-threaded operation of large amounts of data, with StringBuilder, multi-threaded operation of a large number of data, with StringBuffer.

Second, do not use the String class "+" for frequent splicing , because that performance is very poor, you should use the StringBuffer or StringBuilder class.

  Note:Both StringBuilder and StringBuffer have the following methods to display the stringincrease, delete, change, checkFunction.

Add: Insert ();

Deletion: Delete ();

Change: replace ();

Check: IndexOf ();

For specific usage, refer to the Java API documentation.

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