aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static variables location on memory? 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 "Static variables location on memory?" Watch "Static variables location on memory?" New topic
Author

Static variables location on memory?

R Leigh
Greenhorn

Joined: Apr 04, 2013
Posts: 13
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

Joined: May 08, 2013
Posts: 20
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

OCPJP
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Static variables location on memory?