What is Static Block, What is that Use in java?
Ans :
Static Block Executes when the Class Loads. So, It Executes only once.
Here is the Example :
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);
}
}
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);
}
}
When Class Loads it Initializes the Static variables 'a' and 'b'.and executes the Static block.
Prints the message " Static block initialized.".
No comments:
Post a Comment