Multiple Class Initializer and Initializer Block in JAVA

Multiple Class Initializer and Initializer Block in JAVA

Today My one of the Student ask me questions as per following

1) Can we have Multiple Class Initializer and Initializer Block in One Class?
2) If Yes then What will be the Execution Sequence ?

Following Code will help you find answers.

class A 
{

//Class Initializer Block - 1 
static 
{
System.out.println("1");
}

//Class Initializer Block - 2
static
{
System.out.println("2");
}

//Initializer Block - 1 
{
System.out.println("3");
}


//Initializer Block - 2
{
System.out.println("4");
}

A()
{
System.out.println("5");
}

public static void main(String s[])
{
A a = new A();
}
}

Output :

E:\>java A
1
2
3
4
5

No comments:

Post a Comment