Does the garbage collector work on static variables or methods in java?

static fields are associated with the class, not an individual instance.

static fields are cleaned up when the ClassLoader which hold the class unloaded. In many simple programs, that is never.

If you want the fields to be associated with an instances and cleaned up then the instance is cleaned up, make them instance fields, not static ones.


Other than the program, to answer your question

  1. No. Methods are not garbage collected because they don't exist in the heap in the first place.

  2. Static variables belong to the Class instance and will not be garbage collected once loaded (for most of the general Classloaders)


System.gc() does not force garbage collector to run. It is just a suggestion to JVM that probably it is a good time to run garbage collector. See this question - When does System.gc() do anything


You should understand that System.gc(); does not call garbage collector. It just politely asks GC to remove some garbage. GC decides what to do and when to start itself. So, do not expect that you will see any immediate effect when calling System.gc();, assigning null to variable etc.

GC removes all objects that cannot be accessed by any way. So if code exited block where variable was defined the object can be removed. Assiging null removes the reference. Weak reference does not prevent GC from removing the object.

I hope this explanation helps.