my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Garbage Collector Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Garbage Collector " Watch "Garbage Collector " New topic

Garbage Collector

Saurabh Vohra

Joined: Mar 19, 2014
Posts: 4
I have 2 Question (Might be stupid)

Question 1)
I know what happens when we make object reference variable to "null". The object is eligible for GC. because there is no more reference to it.
However , if suppose an object has instance variable. These variable also goes to "null" or it contains its value?


s ----> object_1
instance variable: k--------> object_2

s= "null"

what happens to "k". How many objects are eligible for GC. One or Two?

Question 2) when i make object references equal to other object reference


when i do
x2 start referencing to obj_3. I want to know , x1 will still refer to obj_3 or it lost his reference?

Because i know its x1 bytes are copying to x2 , technically x1 should not loose its object. But still in some problems i find it other way(i.e. x1 loose its object)

Please reply me

Thanks in advance
Sorry for any inconv.
Joanne Neal

Joined: Aug 05, 2005
Posts: 3742
Saurabh Vohra wrote:The object is eligible for GC. because there is no more reference to it.

To be more precise, an object is eligible for garbage collection when there is no reachable reference to it.
So, assuming that s is the only reference to object_1 and object_1.k is the only reference to object_2, then when you set s to null, object_1.k is no longer reachable and so object_2 also becomes eligible for garbage collection.

In your second question, x1 and x2 will both refer to obj_3. If you've ever found anything different then you must have modified x1 somewhere else in your code.

Rico Felix
Ranch Hand

Joined: Mar 08, 2014
Posts: 407

Joanne is correct...

To fully master these object referencing concept, I suggest that you learn some theory behind the stack and heap memory model in Java, then these type of situations become like the saying your ABC's
I agree. Here's the link:
subject: Garbage Collector
It's not a secret anymore!