Thursday, March 12, 2009

Which is garbage collected first: Normal variables or static

Question :Which is garbage collected first: Normal variables or static
variables? (CoreJava)

Answer :Normal variables will be collected first. Lets take a simple example:
Class A is having a static variable s which is used by obj1, obj2 and obj3 of
Class B. Each object of class B is having instance variables a and b (normal
variables). Lets say if obj1 is not being in use since long time, then
automatically the garbage collector will collect the space occupied by obj1.
It will not destroy the static variable S as it is being used by the other two
objects obj2 and obj3. Therefore only normal variables will be destroyed
first.
We can say it in a simple statement that "Variables having less scope will
be destroyed first"

No comments: