2
class Test { public static void main(String[] agrs) { String[] person = new String[20]; String pername = "Peter"; person[0] = pername; pername = null; System.out.println(person[0]); // prints " Peter " on screen System.out.println(pername); // no content in pername. prints " null " } } 

will the pername object eligible for garbage collection ?
i think its eligible because the person[0] contains " Peter " and person[0] doesnt not refer pername anymore .

1 Answer 1

2

Little misunderstanding here. pername or person[0] are just references to the actual instance of String object. Reference live on stack and will be on stack till it is in programs context. The String instance will not be GCed unless both references are null.

Any objects reachable from GC roots cannot be garbage collected. A simple java program will have following GC roots

  1. Local variables in the main method
  2. The main thread
  3. Static variables of the main class

Your case falls under 1st category.

You can read more - Java Memory Management

Sign up to request clarification or add additional context in comments.

10 Comments

but pername has completed its job..it has nothing to do after assigning null to it
Yes I am saying it is just a reference. Both pername and person[0] point to same String instance in the heap memory. Even if you have made pername point to null person[0] is still pointing to the original String instance and hence will not be gced. pername reference will remain on stack till end of your main method. You can point it to some different String instance.
It will be garbage collected but you do not know when it happens because gc has it own algoritm and gc by the way is a quite complicated...
No object can be garbage collected until is is reachable from one of the GC roots and local variables are one of them. Read javabook.compuware.com/content/memory/…
You cannot say pername or person[0] can be GCed. Object living on heap can be GCed and it is just one String in your case and both references point to it. So you cannot say if reference is GCed or not. It is the String object that the reference points to that can be GCed and that will be GCed only when both references are null.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.