来源:https://www.programcreek.com/2009/02/diagram-to-show-java-strings-immutability/

Here are a set of diagrams to illustrate Java String's immutability.

1. Declare a string

The following code initializes a string s.

String s = "abcd";

The variable s stores the reference of a string object as shown below. The arrow can be interpreted as "store reference of".

2. Assign one string variable to another string variable

The following code assign s to s2.

String s2 = s;

s2 stores the same reference value since it is the same string object.

3. Concat string

When we concatenate a string "ef" to s,

s = s.concat("ef");

s stores the reference of the newly created string object as shown below.

In summary, once a string is created in memory(heap), it can not be changed. All methods of String do not change the string itself, but rather return a new String.

If we need a string that can be modified, we will need StringBuffer or StringBuilder. Otherwise, there would be a lot of time wasted for Garbage Collection, since each time a new String is created. 

本文分享自微信公众号 - 彤哥读源码(gh_63d1b83b9e01)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

05-15 14:13