String: The content cannot be changed

The contents of the String object cannot be changed. Changing is an illusion, but what is actually changing is the direction of the heap memory.

For example: String STR = “Hello”; str+” word!” ;

First, the system creates a stack space for “STR”, and then creates a heap space for “Hello”, where “STR” refers to “Hello”. To “STR +” word!” ; “, the system will create two more heap memory space, one for “Word!” “And “Hello Word! And then “STR” in the stack memory space points to “Hello Word!” in the heap memory space. “, followed by “Hello” and “Word! The heap space occupied is reclaimed by the system because it is not referenced. Therefore, concatenating strings with String variables is more memory intensive than the other two String manipulation objects.

StringBuffer: The contents can be changed

A StringBuffer stands for String buffer and itself operates on strings, but unlike String, a StringBuffer can change what is stored in the heap memory space it points to, so it has less memory than String, but is slightly slower. StringBuffer is an operation class, so it must be instantiated to avoid a null pointer exception, whereas String variables can be initialized directly by assignment.

StringBuilder: Single-threaded is recommended for this class, which is faster than StringBuffer

A StringBuilder is a mutable sequence of characters designed as an easy alternative to a StringBuffer when the StringBuffer is being used by a single thread. Because StringBuilder is thread-safe, StringBuffer is thread-safe. Single-threaded is recommended for this class, which is faster than StringBuffer.

Note that both the String class and StringBuffer are decorated with the final keyword. For a final variable, if it is of a primitive data type, its value cannot be changed once initialized; If a variable is a reference type, it cannot be made to point to another object after it is initialized.