I’ve got a simple question. In this code below, why is s3’s value still printed although I set it to null before. It seems gargbage collector won’t get called.
public class Test {
public static void main(String[] args) {
String s1 = "abc", s2 = "def", s3 = "ghj";
String sarr[] = {s1, s2, s3};
s3 = null;
System.gc();
for(int i = 0; i < sarr.length; i++) {
System.out.print(sarr[i] + " "); //prints abc def ghj
}
}
}
Any thoughts would be appreciated.
When you write:
That copies the values of
s1,s2ands3(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 thes1,s2,s3variables 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.
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:
s1,s2, ands3and the elements of the array are references, not objects.Now, to take the example a bit further, consider:
This will print “Hello world” because here we’ve only got a single
StringBuilderobject, which bothsbandarray[0]refer to. Changing the data inside that object (which isn’t the same as changingsbto 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.