Static Initialization Block-SIB
The Static members of the class are stored inside the Class Memory space in heap. The Static members can be accessed directly with the class name there is no need to create objects to access them.
A block of code used to initialize only static variables, which gets executed first when the object is created of that class are Static Initialization Block.
The block of code for Static initialization is as,
static
{
Statements; //static block Statement
}
Whenever a java program is executed it will divide the memory in two parts Heap and Stack. Then it check Main class and load in memory if the class is not loaded. Then it will create its object in class memory. Afterwards loads all the Static members in the allocated space in the class memory, as a results it will load the main() method as it is a static member of java class. The key point to be remembered at this point is that the SIB is not allocated in the Heap. Its just gets in stack executes their task and leave the stack.
For Example
class example {
static int a;
int b;
static {
a = 10;
System.out.println("static block ");
}
}
class Main {
public static void main(String args[]) {
System.out.println(example.a);
}
}
Output:
static block
10
In the above code the static block initializes the variable a with the value 10. So, without creating the object of the example class we are accessing the value of that static member using class name.
0 Comment(s)