Home  >  Article  >  Java  >  Introduction to the reasons for String’s immutability

Introduction to the reasons for String’s immutability

不言
不言forward
2019-03-23 11:17:112868browse

This article brings you an introduction to the reasons for the immutability of String. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In the interview with Maoyan, the interviewer asked why the String string is unchanged. My answer at that time was because the String class was modified with the final keyword. When asked why it was immutable when modified with final, I found that what I said did not make sense. Then I specifically checked why.

The invariance of String, as shown in the figure below, when you change s, s points to a new object and the original object does not change.

Introduction to the reasons for String’s immutability

Look at how the source code is implemented:

Introduction to the reasons for String’s immutability

We see that String is defined as final, so String It is not inheritable. Then we see that the internal implementation of String is a char array and is defined as final. At this time, some people may think that the final modified field cannot be changed after it is created, so it is over, but this is not the case.

Because although value is immutable, only the reference address of value is immutable. But the Array array it refers to is mutable.

final int[] value={1,2,3};
value[2]=100;  //这时候数组里已经是{1,2,100}

So basically the reason why String is immutable is that Sun engineers have encapsulated the value array very well. They do not change the value array in all methods, define it as private, and make the entire String Set it to final to prohibit inheritance to avoid being destroyed by other people inheriting it. So the key to String's immutability is not the role of final.

At the same time, in order to avoid taking up a lot of space due to the immutability of String, Java writers designed a string constant pool

String one = "someString";
String two = "someString";

Introduction to the reasons for String’s immutability

This article is here It’s all over here. For more other exciting content, you can pay attention to the Java Video Tutorial column on the PHP Chinese website!

The above is the detailed content of Introduction to the reasons for String’s immutability. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete