How to Use Static Blocks in Java
- 1). Define the class where you want the static block to be, as in the following sample code:
public class PairOfInts {
static int x,y;
static String status = "Global initialization not yet done";
public PairOfInts(int a,b) {
x=a;
y=b;
}
} - 2). Add the delimiters for the static block inside the class definition, as in the following sample code:
public class PairOfInts {
static int x,y;
static String status = "Global initialization not yet done";
static {
}
public PairOfInts(int a,b) {
x=a;
y=b;
}
} - 3). Add the one-time initialization code between the static block delimiters, as in the following sample code:
public class PairOfInts {
static int x,y;
static String status = "Global initialization not yet done";
static {
// Will execute at most once per execution of the Java application
status = "Global initialization done";
}
public PairOfInts(int a,b) {
x=a;
y=b;
}
}
Source...