java: Source code interpretation of the immutable characteristics of the String class

The immutable meaning of the String class is that the
String object will not change after it is created. Any changes that seem to be made are done by creating a new String object.

For example:

String a = new String("abc");
a = a + "d";

The first statement creates a String object abc, a is a reference to this object

The right side of the second statement creates another String object abcd;

When the second statement is executed, the original object abc is not modified;
Insert picture description here
how immutability is achieved
There are three key points:

1. The String class is modified by final and cannot be inherited; because once inherited is allowed, the method may be rewritten and immutability may be destroyed. This is why the final modification is used;

2. Private final modifies the char[] array; the bottom layer of the string uses a character array to store, this character array is modified by private final to prevent external changes to the string;

3. Any method of the String class will
Insert picture description here
not change the string; why the design is immutable is
mainly for performance considerations, because at the beginning of the design of the java language, it was thought that String would be frequently used, so The constant pool is set up to reuse existing objects as much as possible, which requires existing objects to be immutable;
Insert picture description here

Of course, designing an immutable object can also increase the security of the code to a certain extent. For example, when a variable object is used as the key of a hashMap, if you put the map first and then change the object, it may destroy the uniqueness of the map to the key. Claim;

Learn Java programming with zero foundation, you can join my ten-year Java learning field . Technical exchanges, resource sharing, question and answer, and experience sharing.

Guess you like

Origin blog.csdn.net/weixin_49794051/article/details/112864511