[Android interview question-6] about the string, stringbuffer, stringbuilder class

Source: Internet
Author: User

Question:Briefly describe the differences between string, stringbuffer and stringbuilder, and explain why string is immutable.

Analysis:The main differences between the preceding three types of strings are as follows:

String: A String constant whose attribute is final.

Stringbuffer: string variable, thread security.

Stringbuilder: string variable, non-thread security.

1. The main difference between string and stringbuffer is that string is unchangeable. Execute the following code:

String A = "1"; A = a + "2"; stringbuffer B = new stringbuffer ("2"); B. append ("3 ");

For A and A, after a = a + "2"; is executed, the JVM actually generates a new String object, and then points A to the new object, on the surface, there seems to be nothing special, but the underlying layer actually executes a lot of memory operations, so for those strings that need to change frequently, it is best not to use string; for B, the append operation only adds a character after the original string. Therefore, stringbuffer is recommended for strings that often change content.

2. The main difference between stringbuffer and stringbuilder lies in thread security.

Stringbuilder is non-thread-safe, but it is more efficient than buffer. Therefore, it is best to use stringbuilder to replace stringbuffer in the case of single-thread operations.

Due to the limited level of the author, it is inevitable that there will be errors in the train of thought or code provided for each interview question. Readers should also criticize and correct the question. In addition, I am very grateful to welcome readers to offer more and better interview questions. If you have any comments or suggestions, please refer to the comments.
The blogger Xu fanglei has copyright to this blog article. For Network reprint, please specify the source http://blog.csdn.net/shishengshi. To organize the publications, contact the author.

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.