The static members are shared by all the instances of a class and not reallocated separately to each instance. These are loaded by the classloader moment the class is encountered for the first time.
A related SO question
Please do keep in mind these static members do not belong to a specific class instance.
More info here.
I have included a small code snippet for reference:
@NotThreadSafe
public class Test {
// For all practical purpuose the following block will be only executed once at class load time.
static {
System.out.println("Loaded by the classloader : " + Test.class.getClassLoader());
}
// Keeps track of created instances.
static int instanceCount;
// A simple constructor that increments instance count.
public Test(){
Test.instanceCount++;
System.out.println("instance number : " + instanceCount);
}
public static void main(String[] args) {
System.out.println("Instaintiating objects");
new Test(); new Test();
}
// Where would you expect this line to get printed?
// i.e last statement on the console or somewhere in the middle :)
static {
System.out.println("It should be printed at the end or would it?");
}
}