If you're going to have a job interview tomorrow, the interviewer has a title: Say String/stringbuffer/stringbuilder the difference between them? What would you say? (Brain to fill the answer) today, the small series to chat with you about the string string/stringbuffer/stringbuilder, tell you how to perfect answer the above interviewer's questions, hope to help you.
Analysis of Test centers
This topic also examines string-related. For this topic, we can verify our answers by reading the source code.
The main display is the UML structure of String/stringbuilder/stringbuffer.
Why introduce two other kinds of string processing classes?
To improve the efficiency of string connection. In most cases, the concatenation speed of the string is: stringbuilder>stringbuffer>string.
A string is immutable, so each time it changes its value to its operation, it actually generates a new object and then points the variable reference to the new object;
StringBuffer is different, its operation is the direct manipulation of the reference point to the object, no need to produce new objects, fast, it is thread-safe, in maintaining multi-threaded synchronization, etc. will also consume a bit of performance.
StringBuilder is new after Jdk5, its usage is exactly the same as StringBuffer, but it is thread insecure and best in single threaded because it does not need to maintain thread security and therefore is the fastest.
Is it thread safe?
String string constant (thread safe). StringBuffer string variable (thread safe). StringBuilder string variable (non-thread safe).
The String is immutable, Stringbuffer/stringbuilder is mutable, String/stringbuffer is thread-safe, and StringBuilder is non-thread-safe.
Here is a new question to understand the String.intern () method?
String.intern () looks for a constant pool with a string constant of the same Unicode, if any, returns its reference, or, if not, adds a string of Unicode equal to STR in the constant pool and returns its reference. Therefore, there are many temporary variables that are generated when string concatenation is done using string. It is recommended to use Stringbuffer/stringbuilder more.
Where do you store it?
The string is stored in a constant pool, which has been determined at compile time. The new string () is not a string constant, it has its own address space and is stored in the heap space. The other two are stored in a heap space.
Java face question-string