Java Static Initializer

This Java example uses a static initializer with a static field. A static initializer can set a final value.
Static initializer. Sometimes a class has code that needs to be run before anything happens. This is even before a constructor or field access.
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.

Here: We use two static initializers in a class. The "color" field is assigned by them.

Warning: This example is ambiguous. Color could end up with a different value depending on the order the static initializers are run.

Note: When the bark() method on Dog is called, the static initializers have already run.

Java program that uses static initializer 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(); } } Output Static initializer Static initializer 2 Woof Color is brown
Final 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.
Java program that uses final static 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); } } Output 100
A few notes. 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.
For final values, static initializers offer an advantage. We can create "read-only" values with static initializers and the final keyword.Final
A summary. 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls