Assume String s = new String ("ni"); String s1 = new String ("hao ");
S = s + s1;
System. out. println (s); the result is nihao. Does s actually change? Java bytecode can be compiled at a glance.
We can see that three variables are generated in total for new. The specific process should be: first, there is a "s" variable in the stack pointing to the "ni" object in the heap...
The "s1" variable in the stack points to the "hao" object in the heap.
When executed to s = s + s1;
The system re-creates a larger array in the heap, and then copies "ni" and "hao" in it, then the "s" in the stack points to the new array...
Immutable means that, instead of modifying the original array "ni", it creates a new larger array for expansion, that is, at this time, the array of "ni" objects still exists in the heap, but the "s" variable does not point to the array "ni", but to the new array, this is the difference between StringBuffered and StringBuffered. The latter is modified on the original array to change the value of the original array. StringBuffered is not copied through a new array, it is extended on the basis of the original array... let the variable point to the original array ....