Consider the following scenario:
String dude = "Harold";
//some stuff
dude = "Kumar";
Once dude
is assigned its second value of "Kumar", a whole new object separate from "Harold" comes into existance. What I am wondering is, since there is clearly no use for "Harold" any more, is it garbage collected instantly or at some later time when the JVM deems it appropriate?
UPDATE:
Just because dude
has been set to a new value (object) does not necessarily mean all reference to the old object have been eliminated. If another reference invokes dude
after "Harold" and before "Kumar", it will obviously retain the "Harold" object:
String dude = "Harold";
//some stuff
String interim = dude;
dude = "Kumar";
System.out.println("dude = " + dude);
System.out.println("interim = " + interim);
prints
dude = Kumar
interim = Harold
So there are more considerations than I originally envisioned therefore the initial value doesn't necessarily have to be out of scope after the change.