Translate

Monday 30 December 2013

Static Initialization Blocks with a simple example

A static initialization block is a normal block of code enclosed 
in braces, { }, and preceded by the static keyword. Here is an example: 

static { 
 // whatever code is needed for initialization goes here
} 

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. 
The run-time system guarantees that static initialization blocks are called in the order that they appear in the source code.
For example,
Consider following code.

class StaticBlockDemo 
{ 
static 
{ 
System.out.println("I am in static block 1"); 
} 
static 
{ 
System.out.println("I am in static block 2"); 
} 
public static void main(String args[]) 
{ 
System.out.println("I am in main() method"); 
} 
}

Output:
 
I am in static block 1
I am in static block 2
I am in main() method

So you can see that static block initialization takes place before main() method. 
Static blocks are executed sequentially. Here we have two static blocks. 
Block 1 executed prior to Block 2. 
If we change order of blocks to something like 

static 
{ 
System.out.println("I am in static block 2"); 
} 

static 
{ 
System.out.println("I am in static block 1"); 
} 

 
then output will be

I am in static block 2
I am in static block 1

 
Use of static block:

Generally, static block is used to perform initialization.

No comments:

Post a Comment