When are static variables in Java initialized?
Static variables in Java are initialized when the class is loaded. There are two instances when a class is loaded: when an object is instantiated, and when a static variable or method is accessed.
When instantiating an object of a class for the first time, the class’s bytecode file (.class file) is loaded first, and static variables are initialized to default values (such as the default value of int type being 0), followed by the execution of static code blocks in sequence.
When accessing a class’s static variable or method for the first time, the class’s bytecode file will be loaded, the static variables will be initialized, and then the static code block will be executed.
It is important to note that static variables are only initialized once, whether through instantiating objects or accessing static variables or methods. If static variables are shared by multiple objects, they will all reference the same static variable.