When you write:
// Moved [] to make it more idiomatic
String[] sarr = {s1, s2, s3};
That copies the values of s1
, s2
and s3
(which are references, not objects) into the array. When the statement has executed, the variables are entirely independent of the array. Changing the value of any of the s1
, s2
, s3
variables to refer to a different string doesn't affect the contents of the array at all.
It's exactly the same as with other assignments, e.g.
string x = "hello";
string y = x;
x = null; // Doesn't affect y
and method arguments, too.
Note that the garbage collection part is a red herring here - while obviously understanding this is important to understanding garbage collection, the reverse isn't true. The important points are to understand that:
- The values of
s1
, s2
, and s3
and the elements of the array are references, not objects.
- The values are copied when creating the array, so changing the variable afterwards doesn't make any difference
Now, to take the example a bit further, consider:
StringBuilder sb = new StringBuilder("Hello");
StringBuilder[] array = { sb };
sb.append(" world");
System.out.println(array[0]);
This will print "Hello world" because here we've only got a single StringBuilder
object, which both sb
and array[0]
refer to. Changing the data inside that object (which isn't the same as changing sb
to refer to a different object) makes the change visible however you get at it. This is like me giving the address of my house to two people - if one of them paints my house red, the other person will see that as well.