[Path to Java Development] (8) illustration of immutability of strings
The following figure shows the immutability of Java.
1. Declare a string
String s = "abcd ";
S Stores references to string objects. The arrows in the image below indicate the storage reference.
2. assign a string variable to another string variable.
String s2 = s;
The s2 variable stores the same reference value. Therefore, two variables point to the same string object.
3. Merge strings
S = s. concat ("ef ");
S now stores references to newly generated string objects.
4. Summary
Once a string is created on the memory (HEAP), the string will not change. We should note that all methods of the String class do not change the String itself, but return a new String.
If we need a variable string, we can use StringBuffer or StringBuilder. Otherwise, a new string is created each time.