19

Can I define multiple static blocks?

If possible, why should I define muliple static blocks?

2
  • 6
    For your first question, what happens when you try?
    – beny23
    Apr 4, 2012 at 12:45
  • sounds like a homework question...its your job to demonstrate rigor when asking a question(s). Apr 4, 2012 at 12:48

4 Answers 4

32

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
}
11
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.

7

You can define multiple static blocks. But I don't think it is really necessary. But if you will define, then they will be executed sequentially. i mean the static block defined first will execute first and the next block will execute next.

6

Yes. It is possible to define multiple static blocks in a java class. It helps in modularization of your initialization code, which in turn helps in better understanding and readable nature of the code(As peter mentioned).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.