user1127214
user1127214

Reputation: 3177

Can I define multiple static blocks?

Can I define multiple static blocks?

If possible, why should I define muliple static blocks?

Upvotes: 20

Views: 8339

Answers (4)

dresh
dresh

Reputation: 403

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.

Upvotes: 13

siva.pcu
siva.pcu

Reputation: 61

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).

Upvotes: 6

Peter Lawrey
Peter Lawrey

Reputation: 533530

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
}

Upvotes: 35

Chandra Sekhar
Chandra Sekhar

Reputation: 19502

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.

Upvotes: 8

Related Questions