Thursday, 5 September 2013

how does garbage collection with respect to Strings in Java?

how does garbage collection with respect to Strings in Java?

I am reading about memory management in JVM and that if an object has no
more references to it, it is garbage collected. lets say, I have a program
public test {
public static void main(String[ ] args) {
String name = "hello";
for (int i =0 ; i < 5; i++) {
System.out.println(i);
}
}
}
As you can see, the String name is not used anywhere, so its reference is
kept through out and not garbage collected.
now I have,
String name = "hello"
String name2 = name.substring(1,4)//"ell"
here again, the reference for hello must be present always, and cannot be
garbage collected, since name2 uses it.
so when do these String or any objects get garbage collected, which have
references but are obsolete, i.e. no longer used in code?
I can see one scenario where trimming down an array causes memory leak and
hence setting its reference to null is a good way to garbage collect those
obsolete references.

No comments:

Post a Comment