Sometimes a Java class
has code that needs to be run before anything happens. This is even before a constructor or field access.
Static initializers are confusing. It may be best to avoid them when possible. The order they are called is left undefined, but they are always called by the time they must be.
In a static
initializer, we can initialize static
fields. We can even assign static
final values. These initializers will be run before the class
is used.
static
initializers in a class
. The "color" field is assigned by them.static
initializers are run.bark()
method on Dog is called, the static
initializers have already run.class Dog { static String color; static { // This is a static initializer. // ... It assigns a static String field. System.out.println("Static initializer"); color = "red"; } public void bark() { System.out.println("Woof"); System.out.println("Color is " + color); } static { // Another static initializer. // ... It also assigns the String field. System.out.println("Static initializer 2"); color = "brown"; } } public class Program { public static void main(String[] args) { // Create a new instance and call its method. Dog dog = new Dog(); dog.bark(); } }Static initializer Static initializer 2 Woof Color is brown
static
A final variable is a constant. We cannot reassign it whenever we want to in a program. But in a static
initializer, we can assign final values.
static
initializers and the final keyword.public class Program { final static int size; static { // Assign a final static in a static constructor. size = 100; } public static void main(String[] args) { System.out.println(size); } }100
With the term static
, we indicate something exists only once in memory at a time. A static
initializer is used to assign finals or statics when a class
is first used.