Hi,
Static Initializer is initialised when the class is loaded and even before the main() method is executed. Static variables are also known as class variables.
Instance members (variables/methods) belong to every instance of a class.
Example:
class A
{
static // 1 ==> Static Initializer
{
System.out.println("Static Initializer Executed");
}
static int x=9; // 2 ==> class variable
int y; // 3 ==> Instance variable
boolean answer; // 4 ==> Instance variable
String s; // 5 ==> Instance variable
public static void main(String [] args)
{
A a = new A();
System.out.println(" x = " + A.x );
System.out.println(" y = " + a.y );
System.out.println(" answer = " + a.answer );
System.out.println(" String s = " + a.s );
}
}
Output:
Static Initializer Executed
9
0
false
null
From the above output,it is clear that static initializers are executed even before the main() method is executed.
The instance variables are initialised with the default values, i.e "0" for int, "false" for boolean, "null" for String/any Object.
The static variable "x=9" is accessed by its class name "A".
- Suresh Selvaraj