It's not simple to explain, but I'll try:
The first thing you need to know is that strings are
immutable
- when you declare a string (say "hello there") it cannot be changed, not even slightly. When you try, (Say by adding " Samu!") what happens is that the system adds the lengths of the two strings, allocates enough memory for the result, and copies both of then into it, returning the new string value - the original string is not changed in any way.
The other thing is that when you declare an array:
int[] ar1 = new int[1];
You have done two operations:
1) You have decalared a variable called
ar1
which can reference an array of ints.
2) You have constructed a new array of integers and assigned it's reference to
ar1
What that means is that when you subsequently declare another variable:
int[] ar2 = new int[1];
ar2 = ar1;
You first assign a reference to a new array to it, then overwrite that reference with the one that
ar1
is referring to.
ar1
and
ar2
now both reference that same array in memory.
So when you change the array content via
ar1
it affects the memory that
ar2
is also refering to.
When you do "the same thing" with strings, it all happens the same:
string s1 = "111";
Declares a string variable
s1
, and assigns it a reference to the memory holding "111".
string s2 = s1;
Declares a string variable
s2
, and copies the reference from
s1
. The two variables now refer to the same string in memory: "111"
s2 = "222";
Changes the reference of
s2
to a new string in memory. It does not affect
s1
in any way -
s1
continues to refer to the memory holding "111"