Java strings are immutable ⇨ Once created, the content of the string cannot be changed.
Any methods that seem to modify a String object, like concat
, actually create a new String object with the desired changes. The original String object remains unchanged.
Here are a set of diagrams to illustrate Java String’s immutability.
Initializing string
We can declare a string s
:
String s = "hello";
The variable s stores the reference of a string object as shown below. The arrow can be interpreted as “store reference of”.
Assign one string variable to another
When we assign one string variable to another string variable, following happens:
String s2 = s
Both the object references point to same string object.
Modify string with say concat
When we concatenate a string " world" to s,
s = s.concat(" world");
s
stores the reference of the newly created string object as shown below.
How is array of strings stored?
For string array, only object reference is stored on stack, and it references array of string references on heap. Then these string references refer to string objects in the string pool again on heap.
Video Explanation
Here is the video explanation: