Static block is used for initializing the static variables.This block gets executed when the class is loaded in the memory.
A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program.
The static keyword belongs to the class than an instance of the class.
The static can be:
Variable (also known as a class variable)
Method (also known as a class method)
Block
Nested class
Static block:
Advantage # 1: Static blocks are used to write the logics of application and those logics are executed during class loading
class Test1{
static {
System.out.println("static block 1");
}
static {
System.out.println("static block-2");
}
Test1(){
System.out.println("0-argument constructor");
}
Test1(int a){
System.out.println("1-argument constructor");
}
}
public class StataicBlockDemo1 {
public static void main(String[] args) {
new Test1();
new Test1(10);
}
}
Advantage # 2: Static blocks are used to initialize the static variables
class Test2{
static int eid;
static
{
eid = 222;
}
static void display() {
System.out.println(Test2.eid);
}
}
public class StaticBlockDemo2 {
public static void main(String[] args) {
Test2.display();
}
}
No comments:
Post a Comment