I would like to know if you have a class with only static methods in it, does an actual instance of the class get created somewhere when you call 1st static method?
This is somewhat confusing to understand in terms of memory management as you never actually call the constructor or create an instance of the method explicitly.
If an instance does get created, I would like to better understand where this instance lives and for how long.
No. Calling a
static
method does not require (or create) an instance of aclass
. See also JLS-8.4.3.2static
methods which says (in part)...
Say you have
obviously, a
Foo
object will not be created for callingfunc()
.However, the class
Foo
needs to be loaded in memory; and to the application, there is an object corresponding to the class, which can be referred to asFoo.class
, orClass.forName("Foo")
.A loaded class is not initialized yet. When you call a static method for the 1st time, the class is initialized; some "space" is allocated for static variables, and static initializer code (like
new Bar()
) is executed.This "space" is not visible to application as an object; but it's an in memory data structure too that concerns garbage collections (and other objects it refers to, like
bar
)The class, and the "space", are only eligible for GC when the classloader that loaded the class is eligible for GC. For usual command line applications, that never happens. But for a lot of other applications, class GC is important, and class loading needs to be carefully done.
static
methods belong to the class, not to the object reference. You can callstatic
method and forget about wasting memory on creating an object reference of the class being used, that doesn't happen. When you call anstatic
method on an object reference, you get a compiler warning on the subject. You can even callstatic
methods on a variable of the desired class and this variable can benull
, thestatic
method will be invoked with no problem.