String is a non-variability class, which is characterized by fixed state (there is no method to modify the object). During the lifecycle of the object, its value remains unchanged (it is thread-safe), which is easier to design, implement, and use, not prone to errors, and more secure.
Because the string class supports non-variability, when TMP + = "X" is executed, another object is actually created, the object originally pointed to by TMP becomes garbage (when it has no other references). In this way, a loop will generate n multiple objects, which can be like a waste of memory,
String and stringbuffer are both finall classes. The objects they generate are immutable In the heap, and they are implemented by the attribute char array internally,
So why can stringbuffer append strings to objects? Haha, because the char array in string is finall, that is, a constant, it cannot be changed, and stringbuffer inherits from the abstract class abstractstringbuilder. Its internal implementation relies on its parent class, the char array in abstractstringbuilder is a variable and can be appended with APPEND.