Can I define multiple static blocks?
If possible, why should I define muliple static blocks?
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
These blocks are only executed once when the class is loaded. There can be multiple static initialization blocks in a class that is called in the order they appear in the program.
The answer is 'Yes'. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program.
You can declare a variable static inside a static block because static variables and methods are class instead of instance variable and methods.
yes, you can also make multiple initialisation blocks.
This allows you to place code with the thing initialised.
private static final Map<String, String> map;
static {
// complex code to initialise map
}
private static final DbConnection conn;
static {
// handle any exceptions and initialise conn
}
public class TryInitialisation {
static int[] values = new int[10];
static{
System.out.println("running initialisation block");
for (int i=0; i< values.length; i++)
values[i] = (int) (100.0 * i);
}
static{
System.out.println("running initialisation block");
for (int i=0; i< values.length; i++)
values[i] = (int) (200.0 * i);
}
static{
System.out.println("running initialisation block");
for (int i=0; i< values.length; i++)
values[i] = (int) (300.0 * i);
}
void listValues(){
for (int i=0; i<values.length; i++)
System.out.println(" " + values[i]);
}
public static void main(String[] args) {
TryInitialisation example = new TryInitialisation();
example.listValues();
example = new TryInitialisation(); // referencing a new object of same type
example.listValues();
}
}
here is the output:
running initialisation block
running initialisation block
running initialisation block
0
300
600
900
1200
1500
1800
2100
2400
2700
0
300
600
900
1200
1500
1800
2100
2400
2700
The static blocks were executed serially in the order in which they were declared and the values assigned by the first two static blocks is replaced by the final (third static block).
Also one more thing to observe is that the static initialization block(s) ran only once i.e when the class was loaded by the JVM independent of how many objects were created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With