Diagram to show Java String’s Immutability

A perfect diagram to explain Java String’s immutability.

java_string_immutability

Once a string is created in heap, it can not be changed. We should note that all of 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 StringBuilder usage.

* This beautiful diagram is from the famous “HF SCJP” book.

You may also like:

Leave a comment