What\'s the difference between initialization within a static
block:
public class staticTest {
sta
A static initialization blocks allows more complex initialization, for example using conditionals:
static double a;
static {
if (SomeCondition) {
a = 0;
} else {
a = 1;
}
}
Or when more than just construction is required: when using a builder to create your instance, exception handling or work other than creating static fields is necessary.
A static initialization block also runs after the inline static initializers, so the following is valid:
static double a;
static double b = 1;
static {
a = b * 4; // Evaluates to 4
}
Exception handling during initialization is another reason. For example:
static URL url;
static {
try {
url = new URL("https://blahblah.com");
}
catch (MalformedURLException mue) {
//log exception or handle otherwise
}
}
This is useful for constructors that annoyingly throw checked exceptions, like above, or else more complex initialization logic that might be exception-prone.
The static code block enables to initialize the fields with more than instuction, initialize fields in a different order of the declarations and also could be used for conditional intialization.
More specifically,
static final String ab = a+b;
static final String a = "Hello,";
static final String b = ", world";
will not work because a and b are declared after ab.
However I could use a static init. block to overcome this.
static final String ab;
static final String a;
static final String b;
static {
b = ", world";
a = "Hello";
ab = a + b;
}
static final String ab;
static final String a;
static final String b;
static {
b = (...) ? ", world" : ", universe";
a = "Hello";
ab = a + b;
}
Technically, you could get away without it. Some prefer multiline initialisation code to go into a static method. I'm quite happy using a static initialiser for relatively simple multistatement initialisation.
Of course, I'd almost always make my statics final
and point to an unmodifiable object.
In your example, there is no difference; but often the initial value is more complex than is comfortably expressed in a single expression (e.g., it's a List<String>
whose contents are best expressed by a for
-loop; or it's a Method
that might not exist, so exception-handlers are needed), and/or the static fields need to be set in a specific order.
static
block can be used to initialize singleton instance, to prevent using synchronized getInstance()
method.