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.