Hi I want to know answers for the following questions. Anybody please help me out in this regard. 1)How would garbage collection work on the static variables 2)Will the static variables be garbage collected at all?
Shiva, Just now I was going through a SCJP forum and came through this thread. Barry replied ..
When a class A is loaded an object is created representing the class. This object is an instance of the class Class. From this object you can obtain other objects representing the variables (both static fields and member fields) of the class A. All these objects are held in the heap. The only variables held on the stack are local variables of a method.
So now we should conclude that the static variables are GCed in the same way the instance variable is GCed. The answer to the second part should be " every thing which resides on the heap are created and destroyed".
Mhhh. I'm still considering what you mean with "static variables" and "garbage collected".
Let's take a look at this class:
As soon as someone uses Foo.str, the class loader of the JVM will load the Foo-class. A String-object will be created (on the heap!) and str will be set to refer to this String-object. str itself is on the heap,too, but in the object representing the FOO-class. As soon as someone would execute i.e.
the old String object (the String-object with content "Hello World") is free for garbage collection.
The variable str will be existent as long as the class representation object will reside in the heap. It will "disappear" when the class Foo is unloaded (main thread and all user threads terminated/JVM shuts down).
Variables aren't gc'ed at all. Only objects are gc'ed. A reference variable can *reference* an object, but it *is* not the object.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus