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”.

String-Immutability-1

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.

String-Immutability-2

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.

string-immutability

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.

58 thoughts on “Diagram to show Java String’s Immutability”

  1. Diagram are simple and explainable.
    New Reader of this website.
    Happy that now I learn something sensible.

  2. My bad. I thought I was still on DZone.com (which talks about multiple platforms). This is a Java specific site, so I’ll delete this .Net nonsense.

  3. source from rt.jar:
    substring(beginIndex, count)
    return new String(offset + beginIndex, endIndex – beginIndex, value);

    // Package private constructor which shares value array for speed.
    String(int offset, int count, char value[]) {
    this.value = value;
    this.offset = offset;
    this.count = count;
    }

  4. the diagram is not very well. String is immutability for perfomance operations like as substring. The string have array of char (value), and offset, count.
    s3 = s.substring(0, 1)

    s3.value reference to “abcdef” in heap
    but s3.offset = 0, count = 1

    s3 reference “a”

Leave a Comment