Home
Java
static Initializer
This page was last reviewed on Sep 12, 2023.
Dot Net Perls
Static initializer. Sometimes a Java class has code that needs to be run before anything happens. This is even before a constructor or field access.
A warning. 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.
static
An example. 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.
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
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.
Thus We can create "read-only" values with static initializers and the final keyword.
final
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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 12, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.