Java String class — String String constants
Strings are widely used in Java programming. In Java, strings belong to the pair ****. Java provides the String class to create and manipulate strings.
Note that the value of a String is immutable, which results in a new String being generated every time you operate on a String, which is inefficient and a huge waste of limited memory. Let’s look at this graph of memory changes when operating on String:
As you can see, the initial String value is “hello”, and the new String “world” is appended to the String. This process requires the stack memory to be reconfigured, and the resulting “Hello world” String also needs to be reconfigured. You need to open up memory space three times, which is a huge waste of memory. To deal with frequent string-related operations, Google has introduced two new classes, StringBuffer and StringBuild, to handle these variations.
Java StringBuffer and StringBuilder classes — StringBuffer string variables, StringBuilder string variables
When modifying strings, use the StringBuffer and StringBuilder classes.
Unlike the String class, objects in the StringBuffer and StringBuilder classes can be modified multiple times and do not create new unused objects.
The StringBuilder class was introduced in Java 5, and the biggest difference between it and StringBuffer is that the Methods of StringBuilder are not thread-safe (they cannot be accessed synchronously).
Because StringBuilder has a speed advantage over StringBuffer, the StringBuilder class is recommended in most cases. However, in cases where the application requires thread-safety, the StringBuffer class must be used.
Inheritance structure of the three
The difference between the three:
(1) Difference in character modification (mainly, see above analysis)
(2) the difference in initialization, String can be empty assignment, the latter can not, error
(1) the String
String s = null;
String s = “abc”;
(2) the StringBuffer
StringBuffer s = null; // Null pointer access: The variable result can only be Null at this location
StringBuffer s = new StringBuffer(); // The StringBuffer object is an empty object
StringBuffer s = new StringBuffer(” ABC “); // Create a StringBuffer object with contents that are strings.”
Summary :(1) if you want to manipulate a small amount of data, use String;
(2) multithreaded operation of StringBuffer operating a large number of data StringBuffer;
(3) Single thread operation string buffer operation under a large number of data StringBuilder.
Reprinted from blog.csdn.net/weixin_4110… Thanks for sharing!