Static variable initialization?

Why the static variables are deterministically initialized and local variables aren’t? See how the static variables are implemented. The memory for them is allocated at link time, and the initial value for them is also provided at link time. There is no runtime overhead. On the other hand, the memory for local variables is allocated … Read more

static initialization in interface

Interfaces should not have side-effects and that even applies to static intializers. They would have highly JVM-implementation dependent behavior. Look at the following code public class InterfaceSideEffects { public static void main(String[] args) { System.out.println(“InterfaceSideEffects.main()”); Impl i=new Impl(); System.out.println(“Impl initialized”); i.bla(); System.out.println(“Impl instance method invoked”); Foo f=new Impl(); System.out.println(“Impl initialized and assigned to Foo”); f.bla(); … Read more

Why isn’t a qualified static final variable allowed in a static initialization block?

The JLS holds the answer (note the bold statement): Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple … Read more

How to force a static member to be initialized?

Consider: template<typename T, T> struct value { }; template<typename T> struct HasStatics { static int a; // we force this to be initialized typedef value<int&, a> value_user; }; template<typename T> int HasStatics<T>::a = /* whatever side-effect you want */ 0; It’s also possible without introducing any member: template<typename T, T> struct var { enum { … Read more