Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static variables location on memory?

 
R Leigh
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
SCJP Chapter 3 Question 11:

3. class Beta { }
4. class Alpha {
5. static Beta b1;
6. Beta b2;
7. }
8. public class Tester {
9. public static void main(String[] args) {
10. Beta b1 = new Beta(); Beta b2 = new Beta();
11. Alpha a1 = new Alpha(); Alpha a2 = new Alpha();
12. a1.b1 = b1;
13. a1.b2 = b1;
14. a2.b2 = b2;
15. a1 = null; b1 = null; b2 = null;
16. // do stuff
17. }
18. }
When line 16 is reached, how many objects will be eligible for garbage collection?

Adding to this question... can anyone please explain me the following doubts that have risen out of this question?

1) Instance variables reside inside objects on heap. So on line 11, the alpha object will also have the instance variable "Beta b2" inside it.
Correct? But then where does the "static Beta b1" variable reside?
Since static variables don't reside inside objects as they are initialized per class instead of per instances, then where do they reside?

2) The official answer to the question is "1". The explanation provided is this: "you can still access the other Beta object through the static variable a2.b1—because it's static."
I don't get it!
So if a class B has a static reference to a class A then does it mean that class B will have an access to every instance of class A? Why?
 
Chintu Singh
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static variables are shared by all the classes. These are bind to classes not to the instance.

So a2.b1 refers to b1 even after line 16 gets executed and at this point only 1 object Alpha (a1) is eligible for garbage collection.

Thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic