String

The String class is immutable, meaning that once a String has been created, the sequence of characters contained in it is immutable until the object is destroyed.

Can see that once again give a assignment, not on the original instance objects in the heap to the assignment, but generates a new instance object, and points to the string “456”, points to a new generation of instance objects, an instance of the object before still exists, if not be quoted again, will be garbage collected.

StringBuffer

A StringBuffer object represents a variable string of characters. When a StringBuffer is created, Append (), Insert (), reverse(), setCharAt(), setLength(), and other methods provided by StringBuffer can change the character sequence of this string object. Once the StringBuffer has generated the final desired String, its toString() method can be called to convert it to a String object.

StringBuffer b = new StringBuffer("123"); b.append("456"); // b prints 123456 system.out.println (b);Copy the code

So a StringBuffer object is a string with a mutable character sequence, it doesn’t regenerate an object, and new strings can be concatenated in the original object.

StringBuilder

The StringBuilder class also stands for mutable string objects. In fact, StringBuilder and StringBuffer are basically similar, and the constructors and methods of both classes are basically the same. The difference is that StringBuffer is thread-safe, whereas StringBuilder does not implement thread-safe features, so performance is slightly higher.

How does StringBuffer achieve thread-safety?

The StringBuffer class implements the following methods:

Thus, methods in the StringBuffer class add the synchronized keyword, which adds a lock to the method to keep it thread-safe.

The StringBuilder class implements the following methods:

Improvements to Java9:

Java9 improves the implementation of strings, including String, StringBuffer, and StringBuilder. Prior to Java9, strings used the char[] array to hold characters, so each character of the string was 2 bytes; Java9 strings use a byte[] array with an encoding-Flag field to hold characters, so each character of the string is only 1 byte. So Java9 strings are much more space-efficient, and the string functionality methods are not affected.

Append () :

The append() method equals “+”

So Stringbuffer is actually an array of dynamic strings and append() adds to that array of dynamic strings, For example, “x” + “y” equals the “+” sign. Unlike String, Stringbuffer is put together. String1+String2 and StringBuffer1.append (“y”) print the same, String1+String2 exists at two different addresses. Memory Stringbuffer1. Append (Stringbuffer2) is put together

// By Phyllis Chen from CSDN