Why is the value of String string immutable

1. When we create a new string and assign a value to it, the value of the current object is fixed and will never change. In the String source code, a char array is used to store each character in the string in order, and this char array is decorated with final, which means that once we assign a value to the string, the value of this object will never be Change.

2. But when we assign a new string to the object str in a method in a class, what is its value at this time? For example, at this time str="good", the value of str is good, (you can write an output statement in this method, output this reference, and you will know what's going on) Does it mean that the value of the reference cannot be changed? What changes here is not the value of the reference, but the constant pointed to by the reference str is different, and the life cycle of this reference is the same as that of the current method, that is, the method ends, the reference is killed, and it ends, then it just The reference to good is over, so after this method ends, the value of the reference str is output, which naturally refers to the value pointed to by str, that is, test.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324735994&siteId=291194637