Diagram to show Java String’s 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. String methods 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. Here is an example of using StringBuilder.

Category >> Basics >> Diagram  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";