0

According to Java tutorial Oracle, private static method can be used to initialise static variable. I was just wondering when public static varType myVar = initializeClassVariable(); gets executed? Is it during instantiation of a new instance of the Whatever class or is it only initialised when it is first used?

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        // initialization code goes here
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Thor
  • 9,638
  • 15
  • 62
  • 137
  • During class initialization, see also [JLS-8.7. Static Initializers](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7) – Elliott Frisch Apr 06 '16 at 22:47

1 Answers1

1

As @elliott-frisch suggests, the simple answer is in the JLS:

https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.7 https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4.2

As soon as a class is referenced in a running program it is loaded - which means accessing the class instance itself or creating a new instance of the class.

Loading a class involves scanning classpath for jars which might contain that particular class, reading a resulting jar and loading / validating relevant bytecode from the jar. Having done that, the relevant class-level initialisation blocks of the class are identified and executed. All that happens before any instances of the class are instantiated.

One thing to note is that all of that is confined to a specific classloader. Multiple classloaders may end up doing exactly the same steps for the same class, either at the same or different times. So the same static initialiser can be executed multiple times within the same JVM, although only once within a single classloader instance.

Basically - any reference to a class causes that class to be loaded, but only classes that are referenced are loaded. Just because a referenced class is located within a jar it doesn't mean that other classes within the jar will be loaded.

When does the JVM load classes?

sisyphus
  • 6,174
  • 1
  • 25
  • 35