static member initialization

Hi, Can somebody explain difference between methods to initilize static fields of a class. When is the order of initialization important and which method to prefer if class A is a Java Bean to be invoked from a JSP class A{ public static String HELLO = �HELLO WORLD�; //declare and initialize } class A{ public static String HELLO; public A(){ HELLO = "HELLO WORLD"; //initialize } } class A{ public static String HELLO; static{ HELLO = �HELLO WORLD�; } }

Your first and third methods are equivalent. The middle one, though, is different and potentially bad, as the static variables will remain uninitialized (i.e., null/0/false) until an object of the class is created.

I generally use option 1; I use option 3 if I am forced to because a constructor needs to be in a try-block.

Originally posted by Dan Pollitt: Might it leave the static class member in an inconsistent state in a multi-threaded environment, if it was a more complex piece of initialization?

The second option, using the constructor, can leave the system in an inconsistent state *even in this simple example*. That is, other threads might still see the variable being not or only partly initialized.

Options 1 and 3 are both guaranteed to be thread safe, as far as I know.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus

Just plain wrong. Also, referencing static members non-statically is fugly.

The same as the first one.

Order is important - initializers are executed in the order that they appear. This is in contrast to C# where order of static initialization is not important. For example, in Java, you will receive a compile-time error for a forward reference to a compile-time constant.