Why can't String change


memory distribution

How are str1 and str2 stored?
insert image description here

As shown in the figure: str1 stores the address of value and hash in the heap, and value stores the address of the string abcdef in the heap. That is: str1 points to value, and value points to abcdef
insert image description here

The reason why it cannot be changed (String source code explanation)

Press ctrl and click String to enter the source code of String for analysis, as shown in the figure:
insert image description here

complex situation

The above example belongs to the general situation, so how to explain the following example?
image.png

The explanation is as follows : (If you want to see the result directly, you can slide down to the position marked " Result ")

Details: ( experiment on IDEA )

Generate the corresponding class file and open the location
image.png
image.png

Open the cmd window,
image.png
enter cmd and enter javap -c Test.class, note that Test is the class name you created
image.png

generate
image.png

result

To analyze it, the original code is equivalent to the following code, and the result is as follows:
image.png
image.png

Compared with the original code:
image.png
I believe everyone can understand it here, so I won’t explain too much.

Why is String designed to be immutable?

  1. It is convenient to realize the string object pool. If the String is mutable, then the object pool needs to consider the problem of copy-on-write.
  2. Immutable objects are thread-safe.
  3. Immutable objects are more convenient for caching hash codes, and can be stored in HashMap more efficiently as keys.

Guess you like

Origin blog.csdn.net/weixin_74837727/article/details/130679161