static{
//some statements here
}
//some variables declared here
//some functions defined here
}
Static loop is executed, when the class is loaded.
So without creating the object we can execute this loop.
eg:
When we're loading a DB driver using Class.forName("");
The driver is registered to DriverManager class,
Using the registerDriver()method of DM.
This process done in the static loop of driver class
Got confused !!! Leave that and try this simple example
public class Stat
{
static int i=0;
static{
i=10;
System.out.println(i);
}
public static void main(String []ss)
{
}
}
************************************
If you need to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded.
The following example shows a class that has a static method, some static variables, and a static initialization block.
class UseStatic {
static int a=3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
As soon as the UseStatic class is loaded, all of the static statements are run.First, a is set to 3, then the static block executes(printing a message),and finally, b is initialized to a* 4 or 12.Then main( ) is called,which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static variables a and b,as well as to the local varible x.
Here is the output of the program:
Static block initialized.
x = 42
a = 3
b = 12
No comments:
Post a Comment