Today I had a discussion with my colleague and concluded following points. Kindly throw some light if all are correct or some modification is required.
For the static variables, we have to initialize them after defining the class. To initialize we have to use the class name then scope resolution operator (::), then the variable name. Now we can assign some value. The following code will illustrate the of static member initializing technique.
Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block.
Static variables are initialized only once , at the start of the execution. These variables will be initialized first, before the initialization of any instance variables. A single copy to be shared by all instances of the class. A static variable can be accessed directly by the class name and doesn't need any object.
Initialization of Instance variables But if you declare an instance variable static and final Java compiler will not initialize it in the default constructor therefore, it is mandatory to initialize static and final variables.
1.-3.You cannot exactly know when it happens and so you cannot depend on it. A static constructor will give you a little control what happens when it get called.
public class UtilityClass { // // Resources // // r1 will be initialized by the static constructor static Resource1 r1 = null; // r2 will be initialized first, as static constructors are // invoked after the static variables are initialized static Resource2 r2 = new Resource2(); static UtilityClass() { r1 = new Resource1(); } static void f1(){} static void f2(){} }
4.Static constructors are slow
The exact timing of static constructor execution is implementation-dependent, but is subject to the following rules:
All of your points are correct.
The reason static constructors should be avoided is because the compiler injects code everywhere any method of the class is called to check that the static constructor has been called. This has a negative impact on performance.
What you can do is have a private static field in you class that is assigned a dummy value when the default (or other non static) constructor is called. This initializes all static fields on object creation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With