C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
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